Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using string array in C

Tags:

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.

like image 548
Iwan Sivoronov Avatar asked Dec 27 '25 23:12

Iwan Sivoronov


2 Answers

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;
like image 53
Yunnosch Avatar answered Dec 30 '25 15:12

Yunnosch


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"};
like image 39
mdh.heydari Avatar answered Dec 30 '25 16:12

mdh.heydari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!