2

I'm trying to copy a string into an array of strings, but it doesn't work. I know it is a problem due to memory allocation but I don't see how I could make it work as STRING_LENGTH is a constant.

#define NUMBER_OF_STRINGS 3
#define STRING_LENGTH 255
char message_ecran[NUMBER_OF_STRINGS][STRING_LENGTH];

int i;
char texte3[] = "CVC";
char texte7[] = "iiiiiiiii";

for (i=0;i<=NUMBER_OF_STRINGS;i++)
{
    strcpy(message_ecran[i], texte7);
}
strcpy(message_ecran[0], texte3);

Values of message_ecran after the code:

"CVC"
null
"iiiiiiiii"

expected values

"CVC"    
"iiiiiiiii"
"iiiiiiiii"
3
  • it doesnt't work => cf edit Commented Mar 11, 2013 at 10:41
  • How are you checking the values of message_ecran? Commented Mar 11, 2013 at 10:45
  • 5
    Also, you should not edit the question in response to corrections provided in answers. This makes it confusing for anyone coming to the question later. Commented Mar 11, 2013 at 10:47

3 Answers 3

4

One problem is that you run past the end of message_ecran in the following loop:

for (i=0;i<=NUMBER_OF_STRINGS;i++)

Since message_ecran[NUMBER_OF_STRINGS] is out of bounds, attempting to strcpy() into it results in undefined behaviour.

edit With regards to your edit, I can't reproduce the problem. When I add the following to your latest code:

for (i = 0; i < NUMBER_OF_STRINGS; i++) {
  printf("%d:[%s]\n", i, message_ecran[i]);
}

it prints out

0:[CVC]
1:[iiiiiiiii]
2:[iiiiiiiii]
Sign up to request clarification or add additional context in comments.

3 Comments

for (i=0;i<=NUMBER_OF_STRINGS;i++) will this be OK?
the problem isn't with the for loop, but with the strcpy outside of the loop. The copy outside of the loop puts message_ecran[1] to null
@edi9999: It's bad form to change the question in response to the answers. Instead of helping future users of the site, it just confuses everyone. In any event, I can't reproduce the latest problem you're reporting.
2

The code has undefined behaviour as it accessing beyond the bounds of the array at this line:

for (i=0;i<=NUMBER_OF_STRINGS;i++)

as array indexes are zero-based, and run from 0 to N - 1 where N is the number of elements in the array. This means the valid array indexes for message_ecran are 0 and 1 only, but 2 will be used as an index in the for loop. Change to:

for (i=0;i<NUMBER_OF_STRINGS;i++)

Comments

0

Besides you can start your loop from 1 ie

for (i = 1; i < NUMBER_OF_STRINGS; i++)

since you are later assigning 'texte3' at the zeroth location.

Comments

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.