gpt4 book ai didi

c - 用文件的内容填充字符串数组

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

我编写了一段简短的代码,它将文件的内容复制到初始化的字符串数组中,然后打印该数组。我没有收到任何错误/警告,但程序在运行时仍然没有打印任何内容。代码如下:

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

const int dim = 30;



int main() {

char* arr[dim];
int i = 0;

FILE* fp;
fp = fopen("test.txt", "r+");

if(fp == NULL) {

printf("\nError, breaking...");
return 0;
}

while(i <= dim) {

arr[i] = (char *)malloc(dim*sizeof(char *));
++i;

}

i = 0;

while(fscanf(fp, "%s", arr[i]) != EOF) {

printf("%s: added\n", arr[i]);
++i;

}


}

该文件包含一系列仅由空格和换行符分隔的单词。

最佳答案

纠正以下内容并看看是否有帮助

1) 将 i 初始化为 0,即。我=0;

2)

while(i < dim) { } // it should be < as array start with 0

关于c - 用文件的内容填充字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53600127/

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