gpt4 book ai didi

将字符串复制到二维字符串数组中

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

我有一个 C 代码来标记我的文件内容。我想将每个标记复制/分配给临时变量以将其放入列表中。我的温度被声明为 char *temp[MAX]。这是我的代码,但 strcpy(temp[k], token) 中有问题。当我运行代码时,它强制关闭我的程序。但是,当我删除 strcpy 行/语句时,它会正确运行并且不会强制关闭。但我将 token 复制到 temp 的目标不会实现。有人可以知道为什么会发生这种情况吗?谢谢。

temp 的声明是全局的:char *temp[MAX];

void tokenize(FILE *input){

char *token;
int k=0;

char word[1000];
while(!feof(input)){
fgets(word,1000,input);
token = strtok(word, " \t\n");
while(token!=NULL){
printf("%s\n",token);
strcpy(temp[k], token);
k++;
token= strtok(NULL, " \t\n");
}
}
printf("%s", temp[0]);
}

最佳答案

您需要先为 temp 分配空间,然后才能使用它。是你做的吗?

temp[k] = (char *) malloc(strlen(token)+1);

在将值赋给 temp[k] 之前,将此行添加到您的代码中。

关于将字符串复制到二维字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33981893/

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