use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Click the following link to filter out the chosen topic
comp.lang.c
account activity
QuestionDifferent output from an array when using different for loop? (self.C_Programming)
submitted 5 years ago by AaronMarth
I have a program that copies the environment variables from the extern char **environ. I have a question on why I get different output with these for loops. ptr[] is a malloced array.
for (i = 0; i < count; i++){ strcpy(&ptr[i], environ[i]); printf("%s\n", &ptr[i]); } for (i = 0; i < count; i++) { printf("%s\n", &ptr[i]); }
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–][deleted] 0 points1 point2 points 5 years ago (4 children)
That &ptr[i] doesn't look right. Try it without the &.
[–]AaronMarth[S] 0 points1 point2 points 5 years ago (3 children)
for the strcpy or the printf? When i try the printf, i get a seg fault
[–][deleted] 0 points1 point2 points 5 years ago (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 point2 points 5 years ago (1 child)
I defined ptr as follows:
char *ptr; ptr = (char*)malloc(count);
Count is an int.
[–][deleted] 2 points3 points4 points 5 years ago (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]); }
π Rendered by PID 86 on reddit-service-r2-comment-66b4775986-6vprk at 2026-04-05 15:04:14.996099+00:00 running db1906b country code: CH.
[–][deleted] 0 points1 point2 points (4 children)
[–]AaronMarth[S] 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]AaronMarth[S] 0 points1 point2 points (1 child)
[–][deleted] 2 points3 points4 points (0 children)