【问题标题】:String Array using loop and scanf in c programming [duplicate]在c编程中使用循环和scanf的字符串数组[重复]
【发布时间】:2017-03-02 13:57:13
【问题描述】:

我想使用下面的 scanf 将数据放入数组中,并带有 int 值。

int main (){

int size=5;
int marks[size];
int x;

for(x=0; x<size; x++){
    scanf("%d", &marks[x]);
}

for(x=0; x<size; x++){
    printf("The Element at %d is %d\n", x, marks[x]);
}
getch();
return 0;
}

上面的代码很好并且可以工作,但是我想使用相同的字符串数组,如下例所示,但它不起作用。

int main (){

int size=5;
char *name[size];
int x;

for(x=0; x<size; x++){
    scanf("%s", name[x]);
}

for(x=0; x<size; x++){
    printf("The Element at %s is %s\n", x, name[x]);
}

getch();
return 0;
}

【问题讨论】:

  • char *name[size]; 显然不是您认为的那样... char * 是一个指向字符串的指针,但您必须先让它指向一些分配的内存,然后才能使用它为scanf。 scanf 不会为你分配内存。

标签: c


【解决方案1】:

你没有分配内存来保存你的字符串。做

for(x=0; x<size; x++){
    name[x] = (char*)malloc((size_t)64);
    scanf("%s", name[x]);
    printf("<one>\n");
}

【讨论】:

    猜你喜欢
    • 2016-11-11
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多