c语言 - 如何从代码中删除"incompatible pointer type"警告?



此代码读取输入文本文件,并根据其内容创建输出文件。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OUT 0
#define IN  1
#define MAX 28
#define BLOCK 4000
/* Check whether the character is alphanumeric */
int isAlphanumeric(char c) {
return ('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
('0' <= c && c <= '9');
}
int main(int argc, char *argv[]) {
int c, state = OUT, length = 0, i, j, counter[MAX];
char word[30], longest_word[30];
FILE *input, *output;   /* FILE pointers to open the file */
/* Initialize the counter */
for (i = state; i < MAX; i++)
counter[i] = 0;
/* Open the file */
input = fopen("complete_shakespeare.txt", "r");
output = fopen("word_length_histogram.txt", "w");
/* Keep reading the character in the file */
while ((c = getc(input)) != EOF) {
/* If the character is alphanumeric, record it */
if (isAlphanumeric(c)) {
strncat(word, &c, 1);
}
/* If the character is not alphanumeric, increment the corresponding counter, and additionally, record longest word. */
else {
length = strlen(word);
if (length == 27) strcpy(longest_word, word);
counter[length] += 1;
memset(word, 0, sizeof(word));
}
}
/* If the file ends with a word, record its length */
if (isAlphanumeric(word[0])){
length = strlen(word);
counter[length] += 1;
}
/* print the longest word to the file */
fprintf(output, "%snn", longest_word);
/* Make the histogram */
for (i = 1; i < MAX; i++) {
int dividend = counter[i] / 4000 + 1;
fprintf(output, "%2d %6d ", i, counter[i]);
for (j = dividend; j >= 1; j--){
if (counter[i] != 0)
fprintf(output, "*");
}
fprintf(output, "n");
}
/* Don't forget to close the FILEs */
fclose(input);
fclose(output);
return 0;
}

它产生了正确的输出文件,但每当我编译它时就会出现这个错误

B:\CodeBlocks\Projects\Programming in C\hw_4\Homework_4\main.C|44|警告:从不兼容的指针类型[-Wincompatible指针类型]传递"strncat"的参数2 |

警告似乎来自strncat的唯一一行。有人知道如何补救吗?

变量c被声明为具有类型int
int c, state = OUT, length = 0, i, j, counter[MAX];
^^^^^^

因此,在这个调用中使用的表达式&c

strncat(word, &c, 1);

具有类型CCD_ 3而不是类型char *

为一个字符调用strncat是没有意义的。此外,数组字的值不确定,因为它没有初始化。

char word[30], longest_word[30];

你可以写

char word[30], longest_word[30];
word[0] = '';

然后是下面的

size_t n = 0;
while ((c = getc(input)) != EOF) {
/* If the character is alphanumeric, record it */
if (isAlphanumeric(c)) {
word[n] = ( char )c;
word[++n] = '';
}
/* If the character is not alphanumeric, increment the corresponding counter, and additionally, record longest word. */
else {
if (n == 27) strcpy(longest_word, word);
counter[n] += 1;
n = 0;
word[n] = '';
}
}

也就是说,变量n将跟踪存储在数组word中的字符串的当前长度。

相关内容

  • 没有找到相关文章

最新更新