test2.c: In function 'main':
test2.c:28:3: warning: format '%s' expects a matching 'char *' argument [-Wformat=]
while( fscanf(fp, "%s%s%s" , str)){
^
test2.c:28:3: warning: format '%s' expects a matching 'char *' argument [-Wformat=]
和段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAY_LIMIT 4
#define MAX 100
int main(int argc, char const *argv[]) {
char* array[MAX];
char str[ARRAY_LIMIT];
if (argc != 2)
{
printf( "Wrong number of arguments.");
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == 0){
printf ("failed to open input.txt\n");
exit(1);
}
int j = 0;
while( fscanf(fp, "%s%s%s" , str)){
array[j] = (char *)malloc(sizeof(char)*3);
strcpy(array[j], str);
j++;
}
printf( "%s\n", array[0]);
fclose(fp);
return 0;
}
最佳答案
要读取长度为 3 的字符串,请使用 "%3s"
,而不是 "%s%s%s"
。
段错误来自 EOF 检查的问题。您应该将此作为循环条件:
fscanf(fp, "%3s", str) != EOF
您也没有分配足够大的字符串。它们的大小应该是 sizeof(char)*4
,因为有一个 null 终止字节(感谢评论中的 BLUEPIXY)。
关于c - 我试图将每 3 个字符(不是空格)放入一个数组中,但出现这些错误 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46459730/