【问题标题】:Dynamically memory allocation of a string in a list C列表C中字符串的动态内存分配
【发布时间】:2017-07-24 12:35:29
【问题描述】:

我想从一个文件创建一个列表。这是我的代码。

#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);
}

现在我希望动态分配 str1、str2、str3,但是如果我使用此代码,我会遇到这些错误(重复的成员 str1、str2、str3,预期的 ';' 在结束声明列表中,类型名称需要说明符或限定符)

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;

我正在开发 Xcode。

【问题讨论】:

  • 既不能分配内存,也不能在结构声明中初始化任何结构变量。

标签: c struct dynamic-memory-allocation


【解决方案1】:

您不能在struct 声明中分配内存。您应该在主代码中执行此操作:

struct node {
   char *str;
};

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

另外,sizeof(char *)sizeof(char) 不同。实际上,您可以依靠sizeof(char) 始终为 1,而将其完全排除在外。

【讨论】:

  • STRLENGTH 表示字符串的length,比分配需要的字符串的size小1。建议STRLENGTH+1STRSIZE
猜你喜欢
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
相关资源
最近更新 更多