Understanding pointer arrays

For this particular project I need to utilize the execvp function, because I'm working with multiple threads.

Therefore, I need to store all of the names of a file list into a char array:
char * args[12]

Here is the code where I read in the names.
1
2
3
4
5
6
7
8
char* args[12];
   char filenameList[12];
   int child=1;
	while(!filelist.eof()) {
	char filename[20];
      filelist>>filename;
      args[child]=filename;
      child++;


The problem is when I try to output the filenames at the end (for debugging), all of the entries output as the name of the last filename read.
1
2
   for(int i=1;i<child;i++)
   	cout<<args[i]<<"\n";


Ex:
The list:
x.c
y.c
z.c

output:
z.c
z.c
z.c

I assume it's because they're all pointing to the same address, but I don't know how to make it create a new instance for each name read
char*s are not strings. They're pointers. If you want to have strings, use strings.

What's happening is you're setting all your pointers to point to the same buffer (your "filename" buffer). So when you print them, you'll print whatever the filename buffer holds. Of course since they all point to the same data, they will all print the same string when you try to print them.

What makes this especially bad is that your filename buffer will go out of scope, leaving your args pointers as bad pointers which means they might print random garbage and/or give you an access violation.



Save yourself a bunch of headaches and just use strings when you want to keep track of strings:

1
2
3
4
5
6
7
8
string args[12];  // <- string, not char*
   int child=0;  // <-why were you starting at 1?  arrays start at zero
	while(!filelist.eof()) {
//	char filename[20];  <- no need for this
      filelist>>args[child];  // <- just read directly to your args array
//      args[child]=filename;
      child++;
 



Last edited on
The only issue is that the execvp command requires char pointers
Use c_str() when you need it, and strings otherwise.
+1 Zhuge

1
2
3
4
5
6
7
8
9
10
11
void FuncThatNeedsACharPtr(const char* foo)
{
 //...
}

int main()
{
  string usestrings = "foo";

  FuncThatNeedsACharPtr( usestrings.c_str() );  // <-
}
Topic archived. No new replies allowed.