LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   help w/ pointers vs arrays (http://www.linuxquestions.org/questions/programming-9/help-w-pointers-vs-arrays-54283/)

PTBmilo 04-09-2003 07:58 PM

help w/ pointers vs arrays
 
I'm trying to understand how these things work right now and am running into a question that isn't answered in the book.

suppose that I have something like this:
Code:

.........
      char line[MAXLINE],
            *malloc(),
            *sptr,
            *strtbl[NLINES];

        while((nchars = get_line (line,MAXLINE)) != EOF &&
              (sptr = malloc ((unsigned) nchars +1)) != NULL )
        {
                strcpy (sptr, line);
                strtbl[i++] = sptr;
        }
.......

is it also legal to do this?:
Code:


        char *line,
                *sptr,
                **strtbl;
     
      while((nchars = get_line (line,MAXLINE)) != EOF &&
              (sptr = malloc (nchars +1)) != NULL )
        {
                strcpy (sptr, line);
                *(strtbl + i++) = sptr;
        }

I ask because it does work just the same both ways, but it seems like *(strtbl + i++) would end up pointing to someting else?

is this legal?

AltF4 04-09-2003 09:04 PM

char *strtbl[NLINES] ... reserves an array of NLINES char pointers in memory, strtbl is initialized to point to the first element of the array

char **strtbl ... is a pointer to a char pointer, but is not initialized to point anywhere (and no memory is reserved for storing the data array)


to make things more visible consider this:

typedef char *CPTR;
CPTR strtbl[NLINES]; /* reserves array and points to 1st element */

versus

typedef char *CPTR;
CPTR *strtbl; /* points nowhere */


hope it helps :-)

PTBmilo 04-09-2003 10:57 PM

that does help. thanks.

is there a way around having the constant? maybe something like:

typedef char *CPTR;
CPTR *strtbl = malloc( nArraySize * sizeof(*int));

would this allocate space for nArraySize number of int* 's ?

AltF4 04-10-2003 06:13 PM

>typedef char *CPTR;
>CPTR *strtbl = malloc( nArraySize * sizeof(*int));

*int = not correct
int * = what you need

> would this allocate space for nArraySize number of int* 's ?

would allocate space for nArraySize INT pointers, but "strtbl" would point to CHAR pointers, which is probably not what you inteded :-)


All times are GMT -5. The time now is 03:11 AM.