I am still learning C and have run into some trouble while trying to malloc structures. I have the following structure:
struct data {
int *ref;
int *port;
char data[MAX_STRING];
}temp, valid, invalid;
I intend on using the 'temp' struct to store input data before it is validated, then dependent on the outcome of the validation the struct will be copied to a member of either the valid or invalid array of structs.
int main(){
char inputfile[100];
FILE *file; = fopen("file.txt" , "r");
if (file != NULL){
read_file (file);
}
else{
// Some code here..
}
return 0;
}
void read_file(FILE *file)
{
char buf[1024];
while(!feof (file))
{
struct temp *p_temp = malloc(sizeof(temp));
p_temp->ref = malloc(sizeof(int)); <<<<<<< 'dereferencing pointer to incomplete type'
p_temp->port = malloc(sizeof(int)); <<<<<<< 'dereferencing pointer to incomplete type'
p_temp->data = malloc(sizeof(MAX_STRING)); <<<<<<< 'dereferencing pointer to incomplete type'
fgets(buf, sizeof buf, file);
sscanf(buffer, "%d.%d.%s", p_temp->ref, p_temp->port, p_temp->data);
validate();
}
}
Have I gone about using malloc the correct way with the temporary structure? I am getting the error 'dereferencing to incomplete type'
How would I then go about creating an array of valid and invalid structures that are malloced? Would I create a function such as:
vaild* vaild_record(){
struct vaild *p_vaild = malloc(sizeof(vaild));
if ( p_vaild == NULL)
{
// some code here
}
p_vaild->ref= malloc(sizeof(int));
p_vaild->port = malloc(sizeof(int));
p_vaild->data =(char)malloc(sizeof(STRINGMAX);
if ( p_vaild->ref == NULL || p_vaild->port == NULL || p_vaild->data == NULL)
{
// some code here
}
return 0;
}
Im a bit confused about the whole thing. Any clarity would be great thanks.
p_vaild->data =(char)malloc(sizeof(STRINGMAX);? it does not make sensefeof()like this. Instead test result offgets(), whenNULL, exit loop.