c - 尝试动态选择的菜单..卡在某些部分

标签 c

这个想法是有一个包含 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/

相关文章:

c - 初始化 union 成员 - 使用 MS visual studio

iphone - SQLite iPhone数据插入问题

c - 用于测量通过 LAN 在两个系统之间发送不同数量的数据所需的时间的程序

C 指针地址改变而不赋值

c - 简单修改elf文件的工具?

c - 从结构修改字符串数组

c - 将 makefile 迁移到 Windows 时无法识别通配符

c - 如何动态地将新数据添加到二维数组?

python - 在 C 中解包 (r,g,b) 原始像素缓冲区

c - 具有动态字符串的动态数组。读取字符串字符时出错