Iwan Sivoronov
Iwan Sivoronov

Reputation: 51

Error using string array in C

I am trying to create an array of strings, and print it. Sounds easy, but nothing works for me.

First try was:

int main(){

char ls[5][3]={"aba","bab","dad","cac","lal"};
printf("Das hier: %s", ls[1]);


return 0;
}

But the output is:

Das hier: babdadcaclal a

Even if it should only be:

bab

Next try was after some searches, using:

char* ls[5][3]=.....

instead. This prints:

Das hier: pP@

I was searching for this problem about one day, and I guess, that the problem could be my compiler, but I am not sure about that...
Hope that someone knows what to do, because I am out of ideas. I am using the gcc compiler, if this somehow matters.

Upvotes: 3

Views: 102

Answers (2)

Yunnosch
Yunnosch

Reputation: 26703

This "bab" is a string with an invisible termination '\0' at the end, i.e. of size 4.
To fix, change to

char ls[5][4]={"aba","bab","dad","cac","lal"};

Then, to improve maintainability, use the proposal from David C. Rankins comment, to make an implicitly sized array of TLAs:

char ls[][4]={"aba","bab","dad","cac","lal"};

To use that, use this variable for setting up loops:

size_t n;
n = sizeof ls / sizeof *ls;

Upvotes: 6

mdh.heydari
mdh.heydari

Reputation: 540

Strings in C are null-terminated it means that you need one more byte at the end of the character array to mark it's termination. otherwise you cannot find where the string actually ends.

For example, If I have string "aba" it would be like that at the memory:

'a','b','a','\0'

So you should define you're array as:

char ls[5][4]={"aba","bab","dad","cac","lal"};

Upvotes: 3

Related Questions