0

这个想法是有一个包含 10 个字符串的数组。

尝试使用所选选项动态打印菜单。在这里,我试图将字符串从数组中提取到结构中……但我没有得到它……如果我将字符串直接分配给结构变量,我可以读取它。

请有人解释一下这里出了什么问题?

#include <stdio.h>
#include <stdlib.h>

    typedef struct some_numbers{
       int id;
       char *somestring[10];
       }numb;

    int main()
    {
    int i = 0;         
    numb *new_numb;

    char *arr[10]= {0};

    for(i; i<2; i++)
    {
           printf("Please enter %dth name:\n",i);
           scanf("%s",arr+i);
          //i am printing it agian to confirm that it is stored in said locations
           printf("%s\n",arr+i);
    }

    new_numb = (struct numb *)malloc(sizeof(numb)*4);

    //If i assign the string dirctly then i can print it as follow

    new_numb->somestring[0] = "MY_number";

    printf("%s\n",new_numb->somestring[0]);
       //I am trying to copy string from an arry and print it again....but not working 

    for(i=0; i<2; i++)
    {
             strcpy(new_numb->somestring[i], arr+i);
             printf("%s\n",new_numb->somestring[i]);
    }

    system("PAUSE");
    return 0;    
}
4

1 回答 1

2

您需要为每个char *inarrnew_num->somestring.

随着您创建了一个 10 schar * arr[10]的数组,但它们中的每一个 ( ) 都需要内存来保存字符串。char *arr[0], arr[1]

new_numb->somestring数组类似。

您可以修改代码,例如

for(i; i<2; i++)
{
       printf("Please enter %dth name:\n",i);

       //allocate memory to hold string of max 100 chars, you may want to change that.
       arr[i] = malloc(sizeof(char) * 100);

       scanf("%s",arr+i);
      //i am printing it agian to confirm that it is stored in said locations
       printf("%s\n",arr+i);

}
于 2013-03-15T04:44:07.020 回答