Thread: A question between Array and Pointer

  1. #16
    Registered User moi's Avatar
    Join Date
    Jul 2002
    Posts
    946
    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
    hello, internet!

  2. #17
    Unregistered
    Guest
    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)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting the matrix question..
    By transgalactic2 in forum C Programming
    Replies: 47
    Last Post: 12-22-2008, 03:17 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM