1

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.

1
  • 1
    neither you can allocate memory nor you can initialize any structure variable inside the structure declaration. Commented Mar 4, 2017 at 11:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

STRLENGTH implies the length of a string, which is 1 less than the size of a string as need for the allocation. Suggest STRLENGTH+1 or STRSIZE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.