0

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 :(

4
  • 3
    It would be better to post the code instead of describing the code. If it's correct that name1 is a char, you have big problems... BTW: To copy strings in C use strcpy Commented Jun 7, 2021 at 12:50
  • 2
    Please show the code you have so far. And tell us what doesn't work or which problem you have. Commented Jun 7, 2021 at 12:51
  • 1
    Please edit your question, copy&paste the code and format it as a code block. (For the formatting you can use the {} tool of the editor field.) Commented Jun 7, 2021 at 12:51
  • 1
    {"%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 string strcpy or the memory memcpy... Commented Jun 7, 2021 at 13:00

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Why use sprintf when we have strcpy ?
I tried that and it resulted in like a buffer overflow when running :(
"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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.