c - 我试图将每 3 个字符(不是空格)放入一个数组中,但出现这些错误 :

标签 c

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/

相关文章:

c - WinAPI。如何获得硬盘空闲/忙碌空间

c - 如何用汇编语言获取 'OR' 参数?

检查 pthread 句柄是否正在休眠

c - 在 C 中声明一个大小为 26^5 的 5d 数组

c - scanf或getchar一次10000次然后程序在c中停止

c - 使用 Intel IPP 镜像 BGR(24 位)图像

c - 只需检查 c 中的状态过程

c - 来自不兼容指针类型警告的赋值,我没有 float 的原因?

c - 如何用 kevent() 替换 select() 以获得更高的性能?

c - C 中的错误 "expected ' )' before float "