dynamic array of character arrays

C

cerr

Hi There,

I would like to have a dynamically extending array of character arrays
consisting of filenames:
What I got so far is:
{
const char *dir_path="/home/reg/";
char **filelist=NULL;
char filename[1024]={0};
int items=0;
struct dirent *dp;
// enter existing path to directory below
DIR *dir = opendir(dir_path);
while((dp=readdir(dir))!=NULL){
if(strstr(dp->d_name, "test")!=NULL){
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
filelist=realloc(filelist,sizeof(filelist)+sizeof(filename));
filelist[items++]=&filename;
}
}
}
but i end up getting a seg fault and i'm not exactly sure
why.....anyone?
I a;so get a compiler warning:
test.c:19: warning: assignment from incompatible pointer type
line 19 is where i assign the string pointer to the array: ("filelist
[items++]=&filename;")
Thanks a lot!
Ron
 
S

Seebs

filelist=realloc(filelist,sizeof(filelist)+sizeof(filename));

This is confused.

sizeof(filelist) is not the space allocated, it's the size of a pointer.
You're allocating space in it based on the size of a file name, but what
you need to store in it is pointers to names.

Similarly, storing &filename over and over wouldn't do you any good;
you're just storing the same address over and over, and rewriting its
contents.

Try allocating space for a copy of the filename, then storing those pointers
in the filelist[] elements -- and you need to allocate space for more pointers
to do that.

-s
 
E

Eric Sosman

cerr said:
Hi There,

I would like to have a dynamically extending array of character arrays
consisting of filenames:
What I got so far is:
{
const char *dir_path="/home/reg/";
char **filelist=NULL;
char filename[1024]={0};
int items=0;
struct dirent *dp;

The directory-reading stuff isn't part of C, but that's
not truly the source of your problem. For C purposes, we'll
just say you've got a loop that, every so often, produces a
string in filename[] and you'd like to save those strings
away someplace.
// enter existing path to directory below
DIR *dir = opendir(dir_path);
while((dp=readdir(dir))!=NULL){
if(strstr(dp->d_name, "test")!=NULL){
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
filelist=realloc(filelist,sizeof(filelist)+sizeof(filename));
filelist[items++]=&filename;

Here's the difficulty: You've sort of lost track of what
filelist is, or of what resides where it points. There are
*two* kinds of things you need to store away: The strings
themselves (you can't just leave them in filename[], because
it may get overwritten next time around the loop), and pointers
to the starting points of those strings. So there should be
*two* allocations: One of at least strlen(filename)+1 bytes to
store a copy of the string, and another of sizeof(char*) bytes
to store a pointer to the string's copy. Also, you want all
those pointers to be in consecutive memory locations so you can
treat them as an array.

Let's do the second one first. `filelist' points to the
first char* in an array of `items' char* slots (or when `items'
is zero, `filelist' is NULL). You want it to make room for
another char*, so you need space for `items+1' of them:

filelist = realloc(filelist, (items+1) * sizeof(char*));

Now you have someplace to store a pointer to the copy of
filename[], so let's get some room for the copy:

filelist[items] = malloc(strlen(filename)+1);

Finally, let's copy filename[] into our newly-allocated
string space and increase `items':

strcpy (filelist[items], filename);
++items;

There you have it. Well, almost: You should check the
value returned by malloc() and realloc() before using it,
because they'll return NULL if they can't find the amount of
space you've asked for. That, in turn, means that you should
not immediately store the realloc() value back into the pointer
variable you've resized, because if you store NULL you'll have
lost the only pointer you had to the memory you tried to expand;
you won't even be able to free() it. Lastly, you could use a
somewhat more foolproof way to write sizeof(char*). Putting
it all together, we get

char **temp;
...
temp = realloc(filelist, (items+1) * sizeof *temp);
if (temp == NULL) {
while (--items > 0)
free (filelist[items]);
free (filelist);
// announce failure and return/exit
}
filelist = temp;

filelist[items] = malloc(strlen(filename)+1);
if (filelist[items] == NULL) {
// as above
}

strcpy (filelist[items], filename);
++items;
}
}
}
but i end up getting a seg fault and i'm not exactly sure
why.....anyone?
I a;so get a compiler warning:
test.c:19: warning: assignment from incompatible pointer type
line 19 is where i assign the string pointer to the array: ("filelist
[items++]=&filename;")

Right. You lost track of what pointed to what, but the
compiler didn't, and told you about it.
 
C

cerr

cerr said:
Hi There,
I would like to have a dynamically extending array of character arrays
consisting of filenames:
What I got so far is:
{
  const char *dir_path="/home/reg/";
  char **filelist=NULL;
  char filename[1024]={0};
  int items=0;
  struct dirent *dp;

     The directory-reading stuff isn't part of C, but that's
not truly the source of your problem.  For C purposes, we'll
just say you've got a loop that, every so often, produces a
string in filename[] and you'd like to save those strings
away someplace.
  // enter existing path to directory below
  DIR *dir = opendir(dir_path);
  while((dp=readdir(dir))!=NULL){
    if(strstr(dp->d_name, "test")!=NULL){
      sprintf(filename,"%s%s",dir_path,dp->d_name);
      printf("%s\n",filename);
      filelist=realloc(filelist,sizeof(filelist)+sizeof(filename));
      filelist[items++]=&filename;

     Here's the difficulty: You've sort of lost track of what
filelist is, or of what resides where it points.  There are
*two* kinds of things you need to store away: The strings
themselves (you can't just leave them in filename[], because
it may get overwritten next time around the loop), and pointers
to the starting points of those strings.  So there should be
*two* allocations: One of at least strlen(filename)+1 bytes to
store a copy of the string, and another of sizeof(char*) bytes
to store a pointer to the string's copy.  Also, you want all
those pointers to be in consecutive memory locations so you can
treat them as an array.

     Let's do the second one first.  `filelist' points to the
first char* in an array of `items' char* slots (or when `items'
is zero, `filelist' is NULL).  You want it to make room for
another char*, so you need space for `items+1' of them:

        filelist = realloc(filelist, (items+1) * sizeof(char*));

     Now you have someplace to store a pointer to the copy of
filename[], so let's get some room for the copy:

        filelist[items] = malloc(strlen(filename)+1);

     Finally, let's copy filename[] into our newly-allocated
string space and increase `items':

        strcpy (filelist[items], filename);
        ++items;

     There you have it.  Well, almost: You should check the
value returned by malloc() and realloc() before using it,
because they'll return NULL if they can't find the amount of
space you've asked for.  That, in turn, means that you should
not immediately store the realloc() value back into the pointer
variable you've resized, because if you store NULL you'll have
lost the only pointer you had to the memory you tried to expand;
you won't even be able to free() it.  Lastly, you could use a
somewhat more foolproof way to write sizeof(char*).  Putting
it all together, we get

        char **temp;
        ...
        temp = realloc(filelist, (items+1) * sizeof *temp);
        if (temp == NULL) {
            while (--items > 0)
                free (filelist[items]);
            free (filelist);
            // announce failure and return/exit
        }
        filelist = temp;

        filelist[items] = malloc(strlen(filename)+1);
        if (filelist[items] == NULL) {
            // as above
        }

        strcpy (filelist[items], filename);
        ++items;
    }
  }
}
but i end up getting a seg fault and i'm not exactly sure
why.....anyone?
I a;so get a compiler warning:
test.c:19: warning: assignment from incompatible pointer type
line 19 is where i assign the string pointer to the array: ("filelist
[items++]=&filename;")

     Right.  You lost track of what pointed to what, but the
compiler didn't, and told you about it.

Okay,

Thank you very much for this detailed reply!
Unfortunately it seg faults as well (at the realloc() - I've tried
around but didn't get it running through fine)
My code now looks like this:
{
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
temp = realloc(filelist, (items+1) * sizeof *temp);
if (temp == NULL) {
while (--items > 0)
free (filelist[items]);
free (filelist);
printf("Error reallocating memory for filelist\n");
}
filelist = temp;
filelist[items] = malloc(strlen(filename)+1);
if (filelist[items] == NULL) {
printf("Error reallocating memory for filename\n");
}
strcpy (filelist[items], filename);
++items;
}

Another version that i started playing around with just before I saw
your post would be to allocate new memory for filename in every
iteration with malloc and then save the pointer to it into filelist so
i only would have a list of poiunters in filelist. I guess this would
just be an approach from the other side or is one of these versions to
prefer?

Thanks a lot!
Ron
 
C

cerr

cerr said:
Hi There,
I would like to have a dynamically extending array of character arrays
consisting of filenames:
What I got so far is:
{
  const char *dir_path="/home/reg/";
  char **filelist=NULL;
  char filename[1024]={0};
  int items=0;
  struct dirent *dp;
     The directory-reading stuff isn't part of C, but that's
not truly the source of your problem.  For C purposes, we'll
just say you've got a loop that, every so often, produces a
string in filename[] and you'd like to save those strings
away someplace.
  // enter existing path to directory below
  DIR *dir = opendir(dir_path);
  while((dp=readdir(dir))!=NULL){
    if(strstr(dp->d_name, "test")!=NULL){
      sprintf(filename,"%s%s",dir_path,dp->d_name);
      printf("%s\n",filename);
      filelist=realloc(filelist,sizeof(filelist)+sizeof(filename));
      filelist[items++]=&filename;
     Here's the difficulty: You've sort of lost track of what
filelist is, or of what resides where it points.  There are
*two* kinds of things you need to store away: The strings
themselves (you can't just leave them in filename[], because
it may get overwritten next time around the loop), and pointers
to the starting points of those strings.  So there should be
*two* allocations: One of at least strlen(filename)+1 bytes to
store a copy of the string, and another of sizeof(char*) bytes
to store a pointer to the string's copy.  Also, you want all
those pointers to be in consecutive memory locations so you can
treat them as an array.
     Let's do the second one first.  `filelist' points to the
first char* in an array of `items' char* slots (or when `items'
is zero, `filelist' is NULL).  You want it to make room for
another char*, so you need space for `items+1' of them:
        filelist = realloc(filelist, (items+1) * sizeof(char*));
     Now you have someplace to store a pointer to the copy of
filename[], so let's get some room for the copy:
        filelist[items] = malloc(strlen(filename)+1);
     Finally, let's copy filename[] into our newly-allocated
string space and increase `items':
        strcpy (filelist[items], filename);
        ++items;
     There you have it.  Well, almost: You should check the
value returned by malloc() and realloc() before using it,
because they'll return NULL if they can't find the amount of
space you've asked for.  That, in turn, means that you should
not immediately store the realloc() value back into the pointer
variable you've resized, because if you store NULL you'll have
lost the only pointer you had to the memory you tried to expand;
you won't even be able to free() it.  Lastly, you could use a
somewhat more foolproof way to write sizeof(char*).  Putting
it all together, we get
        char **temp;
        ...
        temp = realloc(filelist, (items+1) * sizeof *temp);
        if (temp == NULL) {
            while (--items > 0)
                free (filelist[items]);
            free (filelist);
            // announce failure and return/exit
        }
        filelist = temp;
        filelist[items] = malloc(strlen(filename)+1);
        if (filelist[items] == NULL) {
            // as above
        }
        strcpy (filelist[items], filename);
        ++items;
    }
  }
}
but i end up getting a seg fault and i'm not exactly sure
why.....anyone?
I a;so get a compiler warning:
test.c:19: warning: assignment from incompatible pointer type
line 19 is where i assign the string pointer to the array: ("filelist
[items++]=&filename;")
     Right.  You lost track of what pointed to what, but the
compiler didn't, and told you about it.

Okay,

Thank you very much for this detailed reply!
Unfortunately it seg faults as well (at the realloc() - I've tried
around but didn't get it running through fine)
My code now looks like this:
{
      sprintf(filename,"%s%s",dir_path,dp->d_name);
      printf("%s\n",filename);
      temp = realloc(filelist, (items+1) * sizeof *temp);
      if (temp == NULL) {
        while (--items > 0)
          free (filelist[items]);
        free (filelist);
        printf("Error reallocating memory for filelist\n");
        }
        filelist = temp;
        filelist[items] = malloc(strlen(filename)+1);
        if (filelist[items] == NULL) {
          printf("Error reallocating memory for filename\n");
        }
        strcpy (filelist[items], filename);
        ++items;
    }

Another version that i started playing around with just before I saw
your post would be to allocate new memory for filename in every
iteration with malloc and then save the pointer to it into filelist so
i only would have a list of poiunters in filelist. I guess this would
just be an approach from the other side or is one of these versions to
prefer?

And this is how far i have gotten with the latter attempt:

filename=malloc((int)strlen(dir_path) + (int)strlen(dp->d_name)+1);
if (temp==NULL)
printf("Error allocating memory for filename\n");
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("filename 0x%x - %s\n",(int)filename, filename);
temp=realloc(filelist,(items+1) * sizeof(char*));
if (temp=NULL){
free(filelist);
printf("Error allocating memory for filelist\n");
}
filelist=temp;
filelist[items++]=filename;

But it is ending up in a
*** glibc detected *** ./test: realloc(): invalid pointer: 0x08048720
***
message... :eek: but why would it not like my realloc() call? :(

Thanks for hints and suggestions,
Ron
 
S

Seebs

filename=malloc((int)strlen(dir_path) + (int)strlen(dp->d_name)+1);

Why are you casting the size_t results from strlen to int?
if (temp==NULL)
printf("Error allocating memory for filename\n");
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("filename 0x%x - %s\n",(int)filename, filename);

Use %p and (void *) if you want to print a pointer.
temp=realloc(filelist,(items+1) * sizeof(char*));

You might want to print out the previous value of filelist before
you do this, because...
if (temp=NULL){

You probably want "==" here. Otherwise, you are always setting
temp to 0, and not executing the following code.

-s
 
B

bartc

cerr said:
Hi There,

I would like to have a dynamically extending array of character arrays
consisting of filenames:
What I got so far is:
{
const char *dir_path="/home/reg/";
char **filelist=NULL;
char filename[1024]={0};
int items=0;
struct dirent *dp;
// enter existing path to directory below
DIR *dir = opendir(dir_path);
while((dp=readdir(dir))!=NULL){
if(strstr(dp->d_name, "test")!=NULL){
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
filelist=realloc(filelist,sizeof(filelist)+sizeof(filename));
filelist[items++]=&filename;
}
}
}
but i end up getting a seg fault and i'm not exactly sure
why.....anyone?

The function addstring() below extends a char** array similar to yours.
Although I've used a 'string' alias for 'char*' because too many *'s around
confuse me.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef char *string;

string* addstring(string* list, string newstr, int* upper) {
/* list is existing list of strings;
newstr is the new entry to add to the end;
*upper is the current number of strings in the list (0 to upper-1);
returns list (might be different start from original), and updates
*upper;
*/
string p;

if (*upper)
list = realloc(list,(*upper+1)*sizeof(string));
else
list = malloc(sizeof(string));
if (list==NULL) return NULL;

p=malloc(strlen(newstr)+1);
if (p==NULL) return NULL;
strcpy(p,newstr);

list[*upper]=p;
++*upper;

return list;
}


int main(void) {
string *filelist=NULL;
int nfilelist=0;
int i;

filelist=addstring(filelist,"One",&nfilelist);
filelist=addstring(filelist,"Two",&nfilelist);
filelist=addstring(filelist,"Three",&nfilelist);

puts("File list:");

for (i=0; i<nfilelist; ++i)
printf("%d : %s\n",i,filelist);

}
 
C

cerr

Why are you casting the size_t results from strlen to int?


Use %p and (void *) if you want to print a pointer.

K, but that doesn't fix the problem cause this is not where the issue
is at.
You might want to print out the previous value of filelist before
you do this, because...

because ...?
You probably want "==" here.  

Hoops yes, I saw that typo just after I posted the last posting... :$
 
E

Eric Sosman

cerr said:
[...]
Thank you very much for this detailed reply!
Unfortunately it seg faults as well (at the realloc() - I've tried
around but didn't get it running through fine)
My code now looks like this:
{
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
temp = realloc(filelist, (items+1) * sizeof *temp);
if (temp == NULL) {
while (--items > 0)

Hah! You've correctly copied my typo. That ought to have
been `--items >= 0', of course.
free (filelist[items]);
free (filelist);
printf("Error reallocating memory for filelist\n");

Okay, but at this point you should *not* just plow blindly
ahead and behave as if the realloc() had succeeded. The code
I offered said to "announce failure and return/exit," not to
"announce failure and keep right on going."
}
filelist = temp;
filelist[items] = malloc(strlen(filename)+1);
if (filelist[items] == NULL) {
printf("Error reallocating memory for filename\n");

Same thing: Once you've detected failure, don't proceed
as if you'd succeeded.
}
strcpy (filelist[items], filename);
++items;
}

Unfortunately, the problems I see in your code now would
only make trouble if malloc() or realloc() failed -- and I imagine
they probably didn't, or you'd have mentioned it. So I think the
reason for the crash must have its origins in the code you didn't
show, somewhere in the stuff surrounding the fragment you've
snipped and exhibited. Please try whittling the code down to the
smallest but complete sample you can devise (that still has the
problem), and post that complete code. Yes, #include's and all;
sometimes they're important, too.
 
C

cerr

cerr said:
[...]
Thank you very much for this detailed reply!
Unfortunately it seg faults as well (at the realloc() - I've tried
around but didn't get it running through fine)
My code now looks like this:
{
      sprintf(filename,"%s%s",dir_path,dp->d_name);
      printf("%s\n",filename);
      temp = realloc(filelist, (items+1) * sizeof *temp);
      if (temp == NULL) {
        while (--items > 0)

     Hah!  You've correctly copied my typo.  That ought to have
been `--items >= 0', of course.
          free (filelist[items]);
        free (filelist);
        printf("Error reallocating memory for filelist\n");

     Okay, but at this point you should *not* just plow blindly
ahead and behave as if the realloc() had succeeded.  The code
I offered said to "announce failure and return/exit," not to
"announce failure and keep right on going."

Exactly but i for now only put this ion a tiny example application - i
will change it once it goes into the real thing but for now i just
have in a tiny void main (void) thingy ;) - i put in a return now :p
        }
        filelist = temp;
        filelist[items] = malloc(strlen(filename)+1);
        if (filelist[items] == NULL) {
          printf("Error reallocating memory for filename\n");

     Same thing: Once you've detected failure, don't proceed
as if you'd succeeded.

same here :)
        }
        strcpy (filelist[items], filename);
        ++items;
    }

     Unfortunately, the problems I see in your code now would
only make trouble if malloc() or realloc() failed -- and I imagine
they probably didn't, or you'd have mentioned it.  So I think the
reason for the crash must have its origins in the code you didn't
show, somewhere in the stuff surrounding the fragment you've
snipped and exhibited.  Please try whittling the code down to the
smallest but complete sample you can devise (that still has the
problem), and post that complete code.  Yes, #include's and all;
sometimes they're important, too.

Uh Okay, luckily my code is fairly small so i just paste the complete
c file:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int main () {
const char *dir_path="/home/reg/";
char **filelist;
char filename[1024]={0};
char **temp;
int items;
struct dirent *dp;
// enter existing path to directory below
DIR *dir = opendir(dir_path);
while((dp=readdir(dir))!=NULL){
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
temp = realloc(filelist, (items+1) * sizeof *temp); /* SHOULD THIS
NOT BE sizeof(*temp)? */
if (temp == NULL) {
while (--items >= 0)
free (filelist[items]);
free (filelist);
printf("Error reallocating memory for filelist\n");
return;
}
filelist = temp;
filelist[items] = malloc(strlen(filename)+1);
if (filelist[items] == NULL) {
printf("Error reallocating memory for filename\n");
return;
}
strcpy (filelist[items], filename);
++items;
}
}
 
C

cerr

cerr said:
[...]
Thank you very much for this detailed reply!
Unfortunately it seg faults as well (at the realloc() - I've tried
around but didn't get it running through fine)
My code now looks like this:
{
      sprintf(filename,"%s%s",dir_path,dp->d_name);
      printf("%s\n",filename);
      temp = realloc(filelist, (items+1) * sizeof *temp);
      if (temp == NULL) {
        while (--items > 0)
     Hah!  You've correctly copied my typo.  That ought to have
been `--items >= 0', of course.
          free (filelist[items]);
        free (filelist);
        printf("Error reallocating memory for filelist\n");
     Okay, but at this point you should *not* just plow blindly
ahead and behave as if the realloc() had succeeded.  The code
I offered said to "announce failure and return/exit," not to
"announce failure and keep right on going."

Exactly but i for now only put this ion a tiny example application - i
will change it once it goes into the real thing but for now i just
have in a tiny void main (void)  thingy ;) - i put in a return now :p


        }
        filelist = temp;
        filelist[items] = malloc(strlen(filename)+1);
        if (filelist[items] == NULL) {
          printf("Error reallocating memory for filename\n");
     Same thing: Once you've detected failure, don't proceed
as if you'd succeeded.

same here :)


        }
        strcpy (filelist[items], filename);
        ++items;
    }
     Unfortunately, the problems I see in your code now would
only make trouble if malloc() or realloc() failed -- and I imagine
they probably didn't, or you'd have mentioned it.  So I think the
reason for the crash must have its origins in the code you didn't
show, somewhere in the stuff surrounding the fragment you've
snipped and exhibited.  Please try whittling the code down to the
smallest but complete sample you can devise (that still has the
problem), and post that complete code.  Yes, #include's and all;
sometimes they're important, too.

Uh Okay, luckily my code is fairly small so i just paste the complete
c file:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int main () {
  const char *dir_path="/home/reg/";
  char **filelist;
  char filename[1024]={0};
  char **temp;
  int items;
  struct dirent *dp;
  // enter existing path to directory below
  DIR *dir = opendir(dir_path);
  while((dp=readdir(dir))!=NULL){
    sprintf(filename,"%s%s",dir_path,dp->d_name);
    printf("%s\n",filename);
    temp = realloc(filelist, (items+1) * sizeof *temp); /* SHOULD THIS
NOT BE sizeof(*temp)? */
    if (temp == NULL) {
      while (--items >= 0)
        free (filelist[items]);
      free (filelist);
      printf("Error reallocating memory for filelist\n");
      return;
    }
    filelist = temp;
    filelist[items] = malloc(strlen(filename)+1);
    if (filelist[items] == NULL) {
      printf("Error reallocating memory for filename\n");
      return;
    }
    strcpy (filelist[items], filename);
    ++items;
  }

}
Ah, sweet! I just figured it out!
I need to define my double pointers to be HULL on declaration:

char **filelist=NULL;
char **temp=NULL;

then it works! :)

Thanks for your help! :)

Ron
 
E

Eric Sosman

cerr said:
[...]
Uh Okay, luckily my code is fairly small so i just paste the complete
c file:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int main () {
const char *dir_path="/home/reg/";
char **filelist;

Aha! In the first-posted version, you initialized
`filelist' to NULL, but in this version the initialization
is missing. `filelist' therefore has an indeterminate
value, a "garbage" value that points to "some random spot."
The first thing you do with this garbage value is pass it
to realloc() -- and it's no wonder realloc() chokes when
you feed it garbage.
char filename[1024]={0};

This initialization, present in both versions, is
useless in both versions. The very first thing you do
with filename[] is overwrite its contents, wiping out the
zeroes you so carefully filled it with. (Wiping out all
the zeroes that matter, anyhow.)
char **temp;
int items;

You've also lost the initialization of `items', which
formerly started at zero but now starts at "garbage." That
will bite you if the garbage value turns out to be something
like -559038737.
struct dirent *dp;
// enter existing path to directory below
DIR *dir = opendir(dir_path);
while((dp=readdir(dir))!=NULL){
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
temp = realloc(filelist, (items+1) * sizeof *temp); /* SHOULD THIS
NOT BE sizeof(*temp)? */

Same thing, either way. You can use sizeof on a type,
in which case parentheses are required: sizeof(char*) or
sizeof(double), for example. Or you can use sizeof on an
expression, in which case the parentheses aren't needed --
if present, they're just part of the expression.

Write (sizeof((*(temp)))), if you like.
 
E

Eric Sosman

cerr said:
[...]
Ah, sweet! I just figured it out!
I need to define my double pointers to be HULL on declaration:

char **filelist=NULL;
char **temp=NULL;

then it works! :)

Thanks for your help! :)

See my reply to your previous message; you haven't quite
solved your problems yet. Also, there's no need to initialize
`temp' -- it's "mostly harmless," but unnecessary.
 
M

Michael Tsang

cerr said:
Hi There,

I would like to have a dynamically extending array of character arrays
consisting of filenames:
What I got so far is:
{
const char *dir_path="/home/reg/";
char **filelist=NULL;
char filename[1024]={0};
int items=0;
struct dirent *dp;
// enter existing path to directory below
DIR *dir = opendir(dir_path);
while((dp=readdir(dir))!=NULL){
if(strstr(dp->d_name, "test")!=NULL){
sprintf(filename,"%s%s",dir_path,dp->d_name);
printf("%s\n",filename);
filelist=realloc(filelist,sizeof(filelist)+sizeof(filename));
filelist[items++]=&filename;
&filename is of type (char (*)[1024]), which is a pointer pointing to an
array object of 1024 char objects. However, filelist[] is of type (char *&),
which is a pointer object pointing to a pointer object pointing to a char
object). They are incompatible. Your program is full of logic errors. You
mentioned sizeof(filelist) in the line containing realloc. Because filelist
is a pointer object, this expression always yields the size of a pointer,
not the array which the pointed object is in. In fact, you must store the
allocated size of the array which the object pointed by filelist is in.
sizeof(filename) is always 1024 as filename is an array object of 1024 char
objects. I'm not sure about the program logic but the realloc expression
always allocates (1024+sizeof(void *)) bytes of memory. The following line
is an error. Instead, you should strcpy(filelist + blah, filename) where
blah is the portion of filelist used.
}
}
}
but i end up getting a seg fault and i'm not exactly sure
why.....anyone?
I a;so get a compiler warning:
test.c:19: warning: assignment from incompatible pointer type
line 19 is where i assign the string pointer to the array: ("filelist
[items++]=&filename;")
Thanks a lot!
Ron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top