C Help: sizeof applied to an incomplete type

Alex

Diamond Member
Oct 26, 1999
6,995
0
0
hey im stuck any help appreciated!

struct filelist *returnvalues;
returnvalues=(struct filelist *)malloc(sizeof(struct filelist));

defined as follows in header file:

struct filelist{
char **filenames;
int count;
};


thanks!
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Originally posted by: franguinho
hey im stuck any help appreciated!

struct filelist *returnvalues;
returnvalues=(struct filelist *)malloc(sizeof(struct filelist));

defined as follows in header file:

struct filelist{
char **filenames;
int count;
};


thanks!

Do not have a C compiler installed on this system to valid this idea, however try:


struct filelist *returnvalues;
returnvalues=(filelist *)malloc(sizeof(filelist));


The structure filelist has already been define to the compiler, it does not need to be redefined which is what you are trying to do.

Another option:

typedef struct filelist
{
char **filenames;
int count;
} FILELIST;


FILELIST*returnvalues;
returnvalues=(FILELIST*)malloc(sizeof(FILELIST));





 

Alex

Diamond Member
Oct 26, 1999
6,995
0
0
Originally posted by: BingBongWongFooey
You don't need to cast it in C.

a_blah = malloc(sizeof(blah));

"ASSIGNMENT MAKES POINTER FROM INTEGER WITHOUT CAST"

bah! :(


edit: oh and for the other guy thanks for the idea but it didnt work either...
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
#include <stdlib.h>

struct filelist{
char **filenames;
int count;
};

int main(void) {
struct filelist * ret;
ret = malloc(sizeof(struct filelist));
free(ret);
}

% gcc test.c
%

works for me...
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
ANSI C 87 and 99 both do not require a cast on the assignment of a type to a void pointer, but both require a cast when attempting to dereference said pointer (obviously).

Regarding the allocation of an incomplete type, you are first going to need to allocate space for the struct itself, and then you are going to need to allocate space for the pointers defined in the struct. Allocating space for the struct as a whole merely allocates sizeof(type*) for each pointer defined in the struct, so you need to allocate memory for where you wish the pointers to reference. Make sense? Full example:

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

struct foo
{
char *s;
int n;
};

int main(void)
{
struct foo *f = malloc(sizeof(struct foo));
f->s = malloc(4);
strncpy(f->s, "foo", 3);

printf("%s\n", f->s);

free(f->s);
free(f);

return 0;
}

 

Alex

Diamond Member
Oct 26, 1999
6,995
0
0
ok im officially a dumbass.... i didnt include the header file at the beginning of the .c file...
i just assumed the compiler did that... bah!


thanks anyway for all the effort guys! :)