Below is my code snippet
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);
}
I want the output to be like:3025931.
Which I am not getting due to incompatible assign type. Please tell me where am i going wrong.
I see two problems here. The first is that the source of the
strcpyisawhere it probably should bex.The second is that
xis not null-terminated. Strings in C are null-terminated character arrays.I would change the two lines:
to:
Here’s a complete program that gives you what you want (it actually prints out the number twice, once in your inner loop character by character and once with the
printfso that you can see they’re the same):Update based on comment:
No, it won’t. That’s because
a[0].codeis a character array (string in this case) and you should be using"%s", not"%c". Changing the format specifier in theprintfshould fix that particular issue.