Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic C pointer question

Tags:

c

I am reading through a "Learn C" book right now and have come across a question I really don't understand. The point of the exercise is to find the problem with this code:

char c;

c = 'a';

printf("c holds the character %c.",c);

..and then it gives the explanation that: "The text string "a" is composed of two characters, both 'a' and the terminating zero byte. The variable c is only a single byte in size. Even if c were 2 bytes long, you couldn’t copy a text string this way. Try copying the text one byte at a time into a variable large enough to hold the text string and its terminating zero byte."

However, when I run the code above - it works perfectly fine. I thought I understood the theory behind why it is bad - the whole terminating 0 at the end of a string thing, so I rewrote the code like this to test:

char c[2];

*c = 'a';

printf("c holds the character %c.",c);

But this generates a problem. I am starting to get confused as to the problem. Wouldn't this 2nd set of code pass the letter 'a' to the pointer at c[0] and then put the terminating 0 at c[1] - fully using the 2 spaces allotted for that array?

like image 221
startuprob Avatar asked Nov 30 '22 05:11

startuprob


1 Answers

The explanation that: "The text string "a" is composed of two characters, both 'a' and the terminating zero byte.

This is true but the 'a' is not "a". 'a' is a single character. So 'a' fits very well in a char.

The example of writing one char by one into a string should look like this:

char str[2];
str[0] = 'a';
str[1] = 0; /* because nothing guarantees array items are initialized to 0 */
printf("str holds the string %s.", str);
like image 174
jdehaan Avatar answered Dec 15 '22 16:12

jdehaan