gpt4 book ai didi

c - 将行读取到字符串数组

转载 作者:行者123 更新时间:2023-11-30 15:44:43 25 4
gpt4 key购买 nike

我正在尝试创建用文件中的行填充字符串数组的函数,但编译器(GCC)仍然给我一个警告。如果我尝试运行编译的应用程序,它会给我“段错误”错误
源代码:

主要

#include <stdio.h>

#include "getAdresses.h"

int main(int argc, char **argv){
char adresses[1024][128];
getAdresses(adresses);
printf("%s", adresses[1]);

}

获取地址

include <stdio.h>

int getAdresses(char **adresses){
FILE *fr;
fr = fopen("adresses", "r");
int i = 0;
while(adresses[i-1][0] != EOF){
fscanf(fr, "%s\n", &adresses[i]);
i++;
}
}

它给了我这个错误:

main.c: In function ‘main’:
main.c:9:2: warning: passing argument 1 of ‘getAdresses’ from incompatible pointer type [enabled by default]
In file included from main.c:3:0:
getAdresses.h:1:5: note: expected ‘char **’ but argument is of type ‘char (*)[128]’

最佳答案

首先,您犯了典型的错误:char **char (*)[128] 相同。后者是地址的类型。

当您尝试在行中取消引用它时,会出现段错误

while(adresses[i-1][0] != EOF)

除了为 i = 0 寻址 [i-1] 会给你带来不好的结果之外,你应该将你的函数定义为

int getAdresses(char (*adresses)[128])

为了能够正确传递二维数组,fscanf 应该扫描到您的实际行缓冲区,如果您逐行读取,请使用 fgets:

while(fgets(adresses[i], 128, fr)) i++;

关于c - 将行读取到字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365115/

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