I’m trying to build an array of strings using popen(), but every index in the array is the last string returned. I’m ultimately just trying to get a directory listing of all files into an array.
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp;
fp = popen("find ~/ -maxdepth 1 -type f", "r");
if (fp == NULL) { printf("Failed to run command\n" ); exit; }
char path[999];
char* rawdata[999];
int i = 0;
while (fgets(path, sizeof(path)-1, fp) != NULL) {
rawdata[i] = path; // Shouldn't this assign every index
i++; // a different string ?
}
pclose(fp);
/* Below, every index is the same string ? */
printf("\n%s", rawdata[0]);
printf("\n%s", rawdata[1]);
printf("\n%s", rawdata[2]);
}
No. You are storing
path, which is the name of an array and therefore decays into the pointer to the beginning of the array. So in fact, all of the elements ofrawdatahave the same value, and that is the address of the arraypath, which never changes.To actually get the contents of
pathcopied over torawdata, you need to allocate memory for it inrawdata[i](malloc) and then usestrcpy. A shortcut for this exists in the standard library calledstrdup:Finally, note that if you are putting a hard cap on the number of elements you are reading, make sure you don’t violate it. That is, once
ireaches999, you shouldn’t read more elements. Therefore: