storing dynamically allocated pointers

This is a discussion on storing dynamically allocated pointers within the C Programming forums, part of the General Programming Boards category; hi still struggling with pointers here,i want to put in names and then dynamically allocate memory to store the names. ...

  1. #1
    Registered User
    Join Date
    Jun 2006
    Posts
    45

    storing dynamically allocated pointers

    hi still struggling with pointers here,i want to put in names and then dynamically allocate memory to store the names. But how do i store he pointer given by malloc into the array of pointers.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    void input (char *array[]){
    
    	char name[21];						//first storing name into name[], 20 char max
    
    	for(i=0; i<10; i++){
    		fgets(name,20,stdin);
    		... = (...) malloc (sizeof (char) * strlen(name));
    	}
    return
    }
    
    int main (void){
    
    	char *names[10];		//room for 10 pointers
    	int count;
    
    return 0;
    }

  2. #2
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    Firstly, Malloc needs no typecasting...
    But, is this what u r trying to do here? U first store the input in "name " , then u r allocating space that is as big as " name " and u are storing the pointer that malloc returns in an array of pointers . back , in main, u wish to print each string

  3. #3
    Registered User
    Join Date
    Jun 2006
    Posts
    45
    yes, the names have to be reachable to other functions called in main, i tryed to do something like

    tab[i] = (char*) malloc (sizeof (char) * strlen(name));
    printf("%s",(*tab)[i]);

    just to check if it was stored succesfully, but hen a processor fault came up.
    Last edited by breaka; 07-21-2006 at 06:33 AM.

  4. #4
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    malloc returns a void pointer, no need to type cast .. read FAQ
    U r allocating the space as large as the string "name", thats fine , u make an element of the array of that array of char pointers u have declared , point to the location , ok, but that location is still not containing anything and u r trying to print it ..
    doing

    Code:
       tab[i] = name ;
       fputs( tab[i] , stdout );
    in ur function might work ,i guess.. just try..

  5. #5
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    tab[i] = (char*) malloc (sizeof (char) * strlen(name));
    printf("%s",(*tab)[i]);
    The following line will allocate enough memory for your string. Note that a string always uses one char more than it's string length for the terminating null character.

    tab[i] = malloc( sizeof (char) * (strlen(name)+1) );

    Keep in mind that malloc does not in any way prepare the data. You have not copied anything to tab[i] yet, so the next line, while syntactically correct, might crash your system or print garbage if you're lucky.

    printf("%s", tab[i]);

    You need to actually copy the contents of the string before printing:

    strcpy( tab[i], name );
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  6. #6
    Registered User
    Join Date
    Jun 2006
    Posts
    45
    ollright it works, but how come you dont have to use a dereference operator to access the content the pointers in the array refer to?
    Last edited by breaka; 07-21-2006 at 10:23 AM.

  7. #7
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    U dont need a de-reference operator because the strcpy takes in arguments that are pointers to chars.. "tab[i]" and "name" are pointers to chars.. The same is the case with fputs..

  8. #8
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    Now that the problem has been solved, I still have one doubt ..

    suppose , in the function, I do,

    Code:
       tab[i] = name ;
       fputs( tab[i] , stdout );
    after allocating space for tab[i].. It prints the name alright,
    But back in main ,

    Code:
             for(count=0;count < 3; count++)
    	   fputs(names[count],stdout);
    It prints junk in the end..

    It works fine with strcpy() as sugggested by nv..

  9. #9
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Did you have a question?

    If you don't write to the memory allocated, how is the memory you allocated supposed to contain the data you would like it to contain? [edit]And leaking the memory you allocated by reassigning the pointer to a local array is not going to help. Understand that arrays cannot be assigned.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  10. #10
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    .. If that is the case, then fputs should print junk inside the function "input " itself .. Its printing whatever I enter correctly .. That is some proof that , it is being stored in the location pointed to by names[i].. It prints junk only in main..yeah, ok i will check the addresses of each of the element in names[i] inside my function.. And i dont think i have done any mistakes in passing the array to hte function..

  11. #11
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by kris.c
    .. If that is the case, then fputs should print junk inside the function "input " itself .. Its printing whatever I enter correctly .. That is some proof that , it is being stored in the location pointed to by names[i]..
    No, it just means that you reassigned the pointer that had previously been given whatever malloc returned to instead point to the local array. When this array was in scope and contained a string, fputs could of course correctly print the string being pointed to.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  12. #12
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    That means ,the array is containing the pointers to the strings, right??
    so, if the issue is only with scope of the array , will making the array global help ?

  13. #13
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by kris.c
    That means ,the array is containing the pointers to the strings, right??
    so, if the issue is only with scope of the array , will making the array global help ?
    Let's not go there. How about we learn how to do this right?
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void input(char *array[], size_t size)
    {
       size_t i;
       for ( i = 0; i < size; i++ )
       {
          char name[21];
          printf("enter text #%d of %d: ", (int)i + 1, (int)size);
          fflush(stdout);
          if ( fgets(name, sizeof name, stdin) != NULL )
          {
             char *newline = strchr(name, '\n');
             if ( newline != NULL )
             {
                *newline = '\0';
             }
             array[i] = malloc(strlen(name) + 1);
             if ( array[i] != NULL )
             {
                strcpy(array[i], name);
             }
             printf("array[%d] = \"%s\"\n", (int)i, array[i]);
          }
       }
    }
    
    int main (void)
    {
       char *names[3];
       size_t i;
       input(names, sizeof names / sizeof *names);
       for ( i = 0; i < sizeof names / sizeof *names; i++ )
       {
          printf("names[%d] = \"%s\"\n", (int)i, names[i]);
       }
       return 0;
    }
    
    /* my output
    enter text #1 of 3: one
    array[0] = "one"
    enter text #2 of 3: two
    array[1] = "two"
    enter text #3 of 3: three
    array[2] = "three"
    names[0] = "one"
    names[1] = "two"
    names[2] = "three"
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  14. #14
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    I appreciate that.. My prog is working perfectly with strcpy() .. I wanted to know why things fail with the other method.. PArticularly because , the contents of the array are valid inside the function .. The problem required the array now to be seen elsewhere too..

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by kris.c
    I appreciate that.. My prog is working perfectly with strcpy() .. I wanted to know why things fail with the other method.. PArticularly because , the contents of the array are valid inside the function ..
    The "contents" of the array are never valid anywhere because you haven't put any contents into the array -- you've merely pointed elsewhere.

    [edit]Why not post what you think ought to work, and perhaps it will be easier to explain why not.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamically creating an array of pointers
    By cs32 in forum C Programming
    Replies: 4
    Last Post: 02-06-2008, 09:42 AM
  2. Dynamically allocated size
    By maverickbu in forum C++ Programming
    Replies: 12
    Last Post: 06-26-2007, 02:16 PM
  3. Dynamically Allocated Array
    By vb.bajpai in forum C Programming
    Replies: 3
    Last Post: 06-17-2007, 09:40 AM
  4. Replies: 5
    Last Post: 12-05-2002, 02:27 AM
  5. Replies: 4
    Last Post: 09-12-2001, 03:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21