下面是我的代码片段
struct encode
{
char code[MAX];
}a[10];
int main()
{
char x[]={'3','0','2','5','9','3','1'};
for(i=0;i<1;i++)
{
printf("%c",x[i]);
//This will printout like 3025931 now I want this to be stored in structure.
}
strcpy(a[0].code,x);
// or
a[0].code=x;//neither works
display();
}
void display()
{
printf("%c",a[0].code);
}
我希望输出如下:3025931。
由于分配类型不兼容,我没有得到。请告诉我哪里出错了。
最佳答案
我在这里看到两个问题。第一个是 strcpy
的源是 a
,它可能应该是 x
。
第二个是 x
不是以 null 终止的。 C 中的字符串是以 null 结尾的字符数组。
我会更改这两行:
char x[] = {'3','0','2','5','9','3','1'};
strcpy(a[0].code, a);
至:
char x[] = {'3','0','2','5','9','3','1', '\0'};
strcpy(a[0].code, x);
这是一个完整的程序,可以满足您的需求(它实际上打印出数字两次,一次在内部循环中逐个字符打印,一次使用 printf
打印,以便您可以看到它们是相同):
#include <stdio.h>
#include <string.h>
#define MAX 100
struct encode {
char code[MAX];
} a[10];
int main() {
int i, j;
char x[] = {'3','0','2','5','9','3','1','\0'};
for(i = 0; i < 1; i++) {
for(j = 0; j < 7; j++) {
printf("%c", x[j]);
}
printf("\n");
strcpy(a[0].code, x);
}
printf("%s\n",a[0].code);
return 0;
}
根据评论更新:
I am sorry. I am new to C. My apologies for not pasting the code snippet correctly in the beginning: "printf("%c",a[0].code);" doesn't display "3025931".
不,不会。这是因为 a[0].code
是一个字符数组(在本例中为字符串),您应该使用 "%s"
,而不是 “%c”
。更改 printf
中的格式说明符应该可以解决该特定问题。
关于c - 关于 char 数组结构的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1911401/