gpt4 book ai didi

c - 访问结构时出现段错误

转载 作者:行者123 更新时间:2023-11-30 15:33:49 25 4
gpt4 key购买 nike

当我执行 level->description 的 printf 命令时,程序给出段错误。我不知道为什么。我应该使用 malloc 来修复它吗?文件 sokoban.dat 的内容(只有 1 行以 '\n' 结尾)是“chicago;addie;story begin here;-----#####-----------| ----#@$.#------------|-----######-----------"

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

typedef struct {
char *name;
char *description;
char *password;
char *map;
struct level *next;
//char *solution;
} LEVEL;

LEVEL* parse_level(char *line) { //parsing from file into the structure
LEVEL level;
char level_name[50];
char level_password[50];
char level_description[100];
char level_map[200];

int i = 0;
int j = 0;
while (line[i] != ';') { //getting level name
level_name[j] = line[i];
i++;
j++;
}
level_name[j]='\0';
level.name=&level_name[0];
//strcpy(&level.name,level_name);
//printf("%s\n",level.name);
printf("%s\n",level_name);
j = 0;
i++;
while (line[i] != ';') { //getting level password
level_password[j] = line[i];
i++;
j++;
}
level_password[j]='\0';
level.password=&level_password[0];
printf("%s\n",level_password);
j = 0;
i++;
while (line[i] != ';') { //getting level description
level_description[j] = line[i];
i++;
j++;
}
level_description[j]='\0';
level.description=&level_description[0];
printf("%s\n",level_description);
j = 0;
i++;
while (line[i] != '\n') { //getting level map
level_map[j] = line[i];
i++;
j++;
}
level_map[j]='\0';
level.map=&level_map[0];
printf("%s\n",level_map);
j = 0;
level.next=NULL;
LEVEL* levelPointer=&level;
return levelPointer;
}
int main(){
FILE *fp = fopen("sokoban.dat", "r");
if( fp == NULL ){
printf("No such file\n");
return 1;
}

char line[500];
//strcpy(line,"");
char c;
int i=0;
while((c = fgetc(fp)) != '\n'){ //reading from file 1 by 1 character
line[i]=c;
i++;
}
printf("%s\n",line);
LEVEL* level;
level=parse_level(line);
//printf("%s\n",level->description); **//!!! this is where error occur**
printf("%s\n",level->map);

return 0;
}

最佳答案

在函数 parse_level() 中,您获取所有局部变量的地址并将其复制到 struct 变量 level 中并返回 级别。所有这些本地地址的副本以及在其生命周期之后使用这些对象都会使您的程序非法并导致 undefined behaviour

在深入研究之前,您应该首先阅读语言基础知识,并了解指针、数组、函数返回值、返回指针等概念。

与您的问题相关的是:

returning a local variable from function in C

Since I can't return a local variable, what's the best way to return a string from a C or C++ function?

Undefined, unspecified and implementation-defined behavior

Undefined behavior and sequence points

The Definitive C Book Guide and List

关于c - 访问结构时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23575102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com