这个想法是有一个包含 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;
}
最佳答案
您需要为 arr
中的每个 char *
以及 new_num->somestring
分配内存。
使用 char * arr[10]
,您创建了一个包含 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);
}
关于c - 尝试动态选择的菜单..卡在某些部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15424818/