I see two problems here. The first is that the source of the strcpy
is a
where it probably should be x
.
The second is that x
is not null-terminated. Strings in C are null-terminated character arrays.
I would change the two lines:
char x[] = {'3','0','2','5','9','3','1'};
strcpy(a[0].code, a);
to:
char x[] = {'3','0','2','5','9','3','1', '\0'};
strcpy(a[0].code, x);
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 printf
so that you can see they're the same):
#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;
}
Update based on comment:
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".
No, it won't. That's because a[0].code
is a character array (string in this case) and you should be using "%s"
, not "%c"
. Changing the format specifier in the printf
should fix that particular issue.