-
Quote:
Originally posted by master5001
Code:
char *nz = "hello";
Isn't exactly cool either. You should get in the habbit of allocating memory.
Code:
char *nz = new char[5];
strcpy(nz, "hello");
or
Code:
char *nz = (char *)malloc(5);
strcpy(nz, "hello");
Your compiler can interpret char *nz = "hello"; to mean one of many things. "hello" could be a static array of chars and nz is pointing to it (this one will run error free) or it could think "hello" is a temporary array of chars and nz points to it (this one will give you a good old seg fault). The fundamental difference between an array and a pointer is that an array has a finite size and a predictable location whereas a pointer is not. Before someone posts how wrong I am, I'll go ahead and point out that there are exceptions however a newbie would best understand what I just said.
yours is wrong too, you need to malloc() 6 chars for null terminator at the end
-
char nz[x]; initializes an ARRAY of x * sizeof(char). that means: if x == 10, 10 bytes are
allocated.
Thus:
char nz[10]; //declare
nz[0] = value; //valid!
nz[9] = value; //valid!
nz[10] = value; //BAD IDEA! you would access memory outside the array nz;
char *nz; just declares a POINTER! A pointer can point to ANY address. BUT IT ONLY POINTS TO IT! no memory is allocated here (except the four bytes (on 32bit systems) to store the address where the pointer points to)
Thus:
char *nz; //declare pointer;
nz[0] = value; //BAD IDEA! you would assign a value to a random location - because the pointer is NOT INITIALIZED!
SO WE INITIALIZE IT:
nz = "hello"; means: nz points to a location in memory, where the string "hello" is stored. so you can now access each letter of hello by using nz[0] up to nz[6] (nz[6] would be the NULL-character)