gpt4 book ai didi

c - 从函数返回字符串数组的指针

转载 作者:太空宇宙 更新时间:2023-11-04 08:35:27 25 4
gpt4 key购买 nike

所以我需要帮助从从文件获取的函数返回字符串数组的指针。字符串不超过 10 个。

输入文件:

3
102
A3B
50

第一个数字是我需要多少个字符串,后面的数字是我需要存储在字符串中的数字。

函数:

   char ** buildArray(){

int x, i;

fscanf(fp, "%d", &x);

char answer[x][10];

for(i=0; i<x; i++){

fscanf(fp, "%s", answer[i]);

}

return answer;
}

我可以正确获取要存储在字符串数组“answer”中的值,但我无法正确返回它。

主要功能:

    int main() {

char * answers;

fp = fopen("data.txt", "r");

if(fp == NULL){
printf("Could not find file.\n");
exit(EXIT_FAILURE);
}

answers = buildAnsArray();

printf("%s", answer[1]); //used as a test to see if i passed the array of strings correctly

fclose(fp);
return 0;
}

在主函数中,当我尝试打印一个值时,它最终崩溃了,或者打印了奇怪的符号

最佳答案

假设这是 C 的某种风格,您试图返回一个指向变量的指针,answer,它在函数内部自动分配,这意味着它会自动释放 当你退出该功能时。因此,要么在该函数外部创建 answer 并将其传入以进行填充,要么明确为其分配空间,以便在函数返回后它可以存活。

关于c - 从函数返回字符串数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26434380/

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