Say I have char Name[100][20] and a struct text with the char variable name1. I have a txt file that contains a name and for which I used sscanf to store it to text.name1. Now I want to store that string into the first row of the 2D array so I did Name[0][20]={"%s",text.name1}; but it results to an error that says expected expression before '{' token.
Can someone please tell me how to fix this :(
1 Answer
With Name[0][20]={"%s",text.name1}; you're trying to initialize the array.
However, {"%s",text.name1}; is not a valid array initializer. To copy text into an array, you can use something like memcpy(), or sprintf():
sprintf(Name[0], "%s", text.name1);
3 Comments
4386427
Why use
sprintf when we have strcpy ?redshorts17
I tried that and it resulted in like a buffer overflow when running :(
itzFlubby
"in like a" : how sure are you about the problem being a buffer overflow? You could try
strcpy like 4386427 pointed out, or if the string isn't null-terminated memcpy(Name[0], text.name1, 20); 20 is the amount of bytes being copied. In your question you set this value to be 20, so I just used that.
name1is achar, you have big problems... BTW: To copy strings in C usestrcpy{}tool of the editor field.){"%s",text.name1}looks like some shorthand from a different language... maybe Ruby? this isn't C code. In C you might want to copy the stringstrcpyor the memorymemcpy...