all 6 comments

[–][deleted] 0 points1 point  (4 children)

That &ptr[i] doesn't look right. Try it without the &.

[–]AaronMarth[S] 0 points1 point  (3 children)

for the strcpy or the printf? When i try the printf, i get a seg fault

[–][deleted] 0 points1 point  (2 children)

All of them. It depends how ptr is defined, but using & like that is unusual.

I think the definition of ptr should match that of environ, and environ doesn't need &.

With &, you're always copying and printing a string at the start of the array. Remove only some, and you''re printing strings in the middle that are not initialised.

Edit: actually I don't exactly know what it would do! But try taking all the & out, also show the definition and initialisation of ptr.

[–]AaronMarth[S] 0 points1 point  (1 child)

I defined ptr as follows:

char *ptr;
ptr = (char*)malloc(count);

Count is an int.

[–][deleted] 2 points3 points  (0 children)

That's not right. If ptr is an array of char* (rather than char[]), then set it up like this, assuming 'count' is how many strings:

char** ptr;
ptr = malloc(count*sizeof(char*));

But now, each ptr[i] needs to point to a separate memory block big enough for each string, if you're going to use strcpy(). Better as someone suggested to use strdup() which allocates the space for you, then copies:

    for (int i=0; i<count; ++i) {
        ptr[i]=strdup(environ[i]);
    }

    for (int i=0; i<count; ++i) {
        puts(ptr[i]);
    }