user7657641
user7657641

Reputation:

Dynamically memory allocation of a string in a list C

I want to create a list from a file. This is my code.

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

struct node {
    char str1[200];
    char str2[200];
    char str3[200];
    struct node *next;
}*start=NULL;

int main(){

FILE *fp;
fp = fopen("file", "r");

while(!feof(fp)){

    struct node *new_node,*current;

    new_node=(struct node*)malloc(sizeof(struct node));
    fscanf (fp,"%s %s %s",new_node->str1,new_node->str2,new_node->str3);
    new_node->next=NULL;


    if(start==NULL) {
        start=new_node;
        current=new_node;
    }
    else {
        current->next=new_node;
        current=new_node;
    }
}

fclose(fp);
}

Now i want str1, str2, str3 are dynamically allocated, but If i use this code I have these errors (duplicate member str1,str2,str3, expected ';' at end declaration list, type name requires a specifier or qualifer)

struct node {
char *str1;
#ERROR
str1=(char*)malloc(sizeof(char*)*200);
char *str2;
#ERROR
str2=(char*)malloc(sizeof(char*)*200);
char *str3;
#ERROR
str3=(char*)malloc(sizeof(char*)*200);
struct node *next;
}*start=NULL;

I'm working on Xcode.

Upvotes: 1

Views: 66

Answers (1)

Bart Friederichs
Bart Friederichs

Reputation: 33531

You cannot allocate memory in the struct declaration. You should do it in your main code:

struct node {
   char *str;
};

struct node node1;
node1.str = malloc(STRLENGTH+1);

Also, sizeof(char *) is not the same as sizeof(char). In fact, you can rely on sizeof(char) to be always 1, and leave it out completely.

Upvotes: 3

Related Questions