gpt4 book ai didi

创建一个字符串数组来保存长字符串中的分割标记?

转载 作者:行者123 更新时间:2023-11-30 19:47:01 25 4
gpt4 key购买 nike

我已经尝试了我所知道的一切,但就是无法创建数组。每次终端都会显示“Segmentation failure: 11”。请帮忙,谢谢!(详细信息在我的评论中)

更新:char*load file(int *numberofwords)返回从txt文件读取的内容(我编出来只是为了测试我的程序如何工作):

Have,a.nice day

Bye.

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


char *loadfile(int *counter) {
int i;
char chr;
char *data;
char *junk;
FILE *GENE;
GENE = fopen("hw7codex.txt", "r");

if (GENE == NULL) {
printf("ERROR - Could not open file.\n");
return NULL;
}


while (1) {
fscanf(GENE, "%s", junk);
(*counter)++;
if (feof(GENE)) break;
}

int wholecounter = 0;
while (1) {
fscanf(GENE, "%c", &chr);
wholecounter++;
if (feof(GENE)) break;
}

data = (char *)calloc(wholecounter, sizeof(char));
if (data == NULL) {
printf("ERROR - Could not allocate memory for the file.\n");
return NULL;
}

rewind(GENE);
i = 0;
while (1) {
fscanf(GENE, "%c", &chr);
data[i++] = chr;
if (feof(GENE)) break;
}
fclose(GENE);

return data;
}






int main(void){

int wordscount=0;

char *temp;

//temp gets a long string from a txt file(which looks like
//"Have,a.nice day"then divides it to separate words:"Have","a", "nice","day"
temp = strtok(loadfile(&wordscount)," ,.\n");

//I want to know how many separate words in this txt file
printf("%s\n", loadfile(&wordscount)); //it prints out 5
printf("%d\n", wordscount); //it prints out 'Have,a.nice day\nBye'


//I want to create a string array here to hold all those words , but I keep failing
char array[wordscount][40];

int j=0;
while (temp != NULL){
strcpy(array[j], temp);
j++;
temp = strtok (NULL, " ,.\n");
}


for (j = 0; j < wordscount; j++){
printf("%s\n", array[j]);
}

最佳答案

char array[wordscount][40];如果您的编译器不支持 VLA,则这是非法的。您应该声明一个指向字符串的指针数组,然后手动分配内存:

char** array;
int i;
array = (char**)malloc(wordscount * sizeof(char*)); //

for ( i = 0; i < wordscount; i++) {
array[i] = (char*)malloc(40 * sizeof(char)); // make sure the length of every word is less than 40
};

编辑:
如果loadfile()返回你写的内容(不知道你如何实现 loadfile() ,你应该为函数中的字符串分配内存)和 wordscount是 5,那么这里是一个可以正常工作的示例:

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

int main(void){

int wordscount = 5;

char *temp;
char buf[128] = "Have,a.nice day\nBye";

temp = strtok(buf, " ,.\n");

char** array;
int i;
array = (char**)malloc(wordscount * sizeof(char*)); //

for ( i = 0; i < wordscount; i++) {
array[i] = (char*)malloc(40 * sizeof(char)); // make sure the length of every word is less than 40
};

int j = 0;
while (temp != NULL){
strcpy(array[j], temp);
j++;
temp = strtok (NULL, " ,.\n");
}

for (j = 0; j < wordscount; j++){
printf("%s\n", array[j]);
}
}

在您的 loadfile() 中, junk是一个未初始化的指针,所以这一行: fscanf(GENE, "%s", junk);将导致未定义的行为。

关于创建一个字符串数组来保存长字符串中的分割标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22774969/

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