I’m struggling to break the char array for this one.
My problem is that when I add a non-null char to the end of the array it simply won’t print out the expected garbage at the end of it (have tried moving the initialisation of the variables around to see if that helps.
My initial thoughts were:
- I’m getting super lucky with where these variable are getting stored in memory and name jsut so happens to get stored each time just before a null character (e.g. location of (name[3] + 1) == ‘\0’ in memory).
- the compiler is taking pity on me and adding a null character to the end of the array (seems to go against everything that I’ve been reading online).
I can’t seem to get to the bottom of it from the various forums online, and there are no references to point two anywhere that I can see (my next item to investigate was the cc release notes.
For reference
>> cc --version
>> cc (Ubuntu 9.3.0-10ubuntu2) 9.3.0)
I was initially following the book on Windows 10 with cygwin up to and including ex11. In case that was causing the problem (or in this case a lack of a problem!), however unlikely this is, I took the opportunity to finally get around to installing Ubuntu on my machine alongside Windows. I get the same result on both OS’s. By my thinking this significantly reduces the likelihood of point one causing the issue.
Any thoughts on where I’ve gone wrong?
ex11.c is below built with the Makefile tags as recommended in ex2
CFLAGS=-Wall -g
#include <stdio.h>
int main(int argc, char *argv[])
{
int numbers[4] = { 0 };
char name[4] = { 'a', 'a', 'a', 'a' };
// first, print the out raw
printf("numbers: %d %d %d %d\n",
numbers[0], numbers[1], numbers[2], numbers[3]);
printf("name each: %c %c %c %c\n",
name[0], name[1], name[2], name[3]);
printf("name: %s\n", name);
// set up the numbers
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
// setup up the name
name[0] = 'Z';
name[1] = 'e';
name[2] = 'd';
name[3] = 'A';
// print them out initialised
printf("numbers: %d %d %d %d\n",
numbers[0], numbers[1], numbers[2], numbers[3]);
printf("name each: %c %c %c %c\n",
name[0], name[1], name[2], name[3]);
printf("name: %s\n", name);
// another way to use name
char *another = "Zed";
printf("another: %s\n", another);
printf("another each: %c %c %c %c\n",
another[0], another[1], another[2], another[3]);
return 0;
}
This returns
./ex11
numbers: 0 0 0 0
name each: a a a a
name: aaaa
numbers: 1 2 3 4
name each: Z e d A
name: ZedA
another: Zed
another each: Z e d