我的代码给了我一个分段错误。我调试它,并在执行strcpy时发生错误。代码试图从文本文件中提取数据并将其存储到结构数组中。我计划使用strcpy将文本文件的数据存储到结构中。知道为什么会这样吗?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int input( char *s, int length);
void main(){
char *tok;
char *buffer;
size_t bufsize = 32;
size_t characters;
FILE *f;
char *file_name;
char line[255];
int currentRoom;
int count = 0;
typedef struct {
char room_n;
char description[100];
char room_north;
char room_south;
char room_west;
char room_east;
} room;
//Creating an array of structs
room record[1000];
while(1){
buffer = (char *)malloc(bufsize * sizeof(char));
if(buffer == NULL){
perror("Unable to allocate buffer");
exit(1);
}
printf("Enter a command: ");
characters = getline(&buffer, &bufsize, stdin);
if(strcmp(buffer,"exit\n") == 0){
printf("Exiting...\n");
exit(1);
}
tok = strtok(buffer, " \n"); // Tokenize input
printf("%s is the token \n", tok);
if (strcmp(tok,"loaddungeon") == 0){
file_name = strtok(NULL, "\n");
printf("file name : %s \n", file_name);
f = fopen(file_name,"r");
while (fgets(line, sizeof(line), f) != NULL)
{
char val1[128];
char val2[128];
char val3[128];
char val4[128];
char val5[128];
char val6[128];
strcpy(val1, strtok(line, "$"));
strcpy(val2, strtok(NULL, "$"));
strcpy(val3, strtok(NULL, " "));
strcpy(val4, strtok(NULL, " "));
strcpy(val5, strtok(NULL, " "));
strcpy(val6, strtok(NULL, " "));
//Segmentation fault error occurs here
strcpy(record[count].room_n, val1);
答案 0 :(得分:2)
strcpy()的定义是:
char *strcpy(char *dest, const char *src)
其中 -
dest - 这是指向目标数组的指针 内容将被复制。
src - 这是要复制的字符串。
在您的代码中,传递给strcpy()的参数是char
和char *
:
strcpy(record[count].room_n, val1);
如结构中所定义:
typedef struct {
char room_n; //room_n declared as 'char'
char description[100];
char room_north;
char room_south;
char room_west;
char room_east;
} room;
建议:
为room_n
分配内存以指向。将声明更改为
char room_n[128];