gpt4 book ai didi

c - strcpy 给我段错误

转载 作者:行者123 更新时间:2023-11-30 20:11:13 24 4
gpt4 key购买 nike

我的代码给我带来了段错误。我调试了一下,执行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);

最佳答案

strcpy()的定义是:

char *strcpy(char *dest, const char *src)

哪里-

  • dest -- 这是指向目标数组的指针内容要复制。

  • src -- 这是要复制的字符串。

在您的代码中,传递给 strcpy() 的参数是 charchar * :

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];

关于c - strcpy 给我段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799730/

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