I am currently learning C and am trying to fill an array of strings with a loop as a simple exercise. I am just trying to fill all 4 elements with the word "Hello". When I print my array out I get output like this:
messages[0] = HelloHelloHelloHello
messages[1] = HelloHelloHello
messages[2] = HelloHello
messages[3] = Hello
For an odd reason, the first 3 elements have the word hello repeating mulitple times. I do not understand why this is happening.
Here is my code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char messages[4][5];
for(int i = 0; i < 4; i++){
//&messages[i] = (char *)malloc(5);
strcpy(messages[i],"Hello");
}
for(int i = 0; i < 4; i++){
printf("messages[%d] = %s\n", i, messages[i]);
}
return 0;
}
I also tried looking up way to do this, and I found something about using malloc, but I just kept getting compiler errors.
