Thread: Simple array/pointer problem...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Location
    Maine
    Posts
    11

    Question Simple array/pointer problem...

    If I declare a character array and want to add an item to the array, without having it point to that item, for example:

    Code:
    Code:
    char * arr[50];
    char temp[255];
    
    for(loop where temp is always changing)
    {
      array[i] = temp;
    }
    for(loop through array)
      printf("%s", array[i]);
    Results:
    Code:
    same
    same
    same
    same
    How can I make it so that all elements in the array do not point to the current temp value, but point to what temp was at that time? I know its a pointer problem, but I don't really understand pointers that well.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    you have to allocate new memory for each element of the array
    Code:
    char * array[50];
    char temp[255];
    
    for(loop where temp is always changing)
    {
      array[i] = malloc(strlen(temp)+1);
      strcpy(array[i],temp);
    }
    for(loop through array)
      printf("%s", array[i]);
    or just hard-code the memory (not a very good idea for a large array!)
    Code:
    char  array[50][255];
    char temp[255];
    
    for(loop where temp is always changing)
    {
      strcpy(array[i], temp);
    }
    for(loop through array)
      printf("%s", array[i]);

  3. #3
    Registered User
    Join Date
    Mar 2006
    Location
    Maine
    Posts
    11
    EDIT: Thanks for your help.
    Last edited by smoothdogg00; 03-14-2006 at 10:03 PM.

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Don't forget to free() the memory.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A simple file I/O problem
    By eecoder in forum C Programming
    Replies: 10
    Last Post: 10-16-2010, 11:00 PM
  2. Problem in simple code.
    By richdb in forum C Programming
    Replies: 6
    Last Post: 03-20-2006, 02:45 AM
  3. Problem in very simple code
    By richdb in forum C Programming
    Replies: 22
    Last Post: 01-14-2006, 09:10 PM
  4. Simple Initialization Problem
    By PsyK in forum C++ Programming
    Replies: 7
    Last Post: 04-30-2004, 07:37 PM
  5. Simple OO Problem
    By bstempi in forum C++ Programming
    Replies: 1
    Last Post: 04-30-2004, 05:33 PM