带有 int 指针的转换代码

标签 c type-conversion

#include <stdio.h>
#include <ctype.h>

void readFile(FILE *file);
void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces);
void printMessage(int *alpha, int *digit, int *punct, int *spaces);

int main( void ) {
FILE *file = NULL;
readFile(file);
return 0;
}

void readFile(FILE *file) {
file = fopen("/Users/AdmiralDanny/Desktop/testFile.txt", "r");
int *alpha = NULL, *digit = NULL, *punct = NULL, *space = NULL;
if (file) {
  count(file, alpha, digit, punct, space);
  fclose(file);
} else {
  perror( "error opening the file" );
}
}

void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces) {
  int ch;

 while ((ch = fgetc(file)) != EOF ) {
   if (isalpha(ch) != 0) {
  ++alpha;
  } else if (isdigit(ch)) {
  ++digit;
  } else if (ispunct(ch)) {
  ++punct;
  } else if (isspace(ch)) {
    ++spaces;
  }
}
 printMessage(alpha, digit, punct, spaces);
}

void printMessage(int *alpha, int *digit, int *punct, int *spaces) {
printf( "alphabetic characters: %d\n", alpha );
printf( "digit characters: %d\n", digit);
printf( "punctuation characters: %d\n", punct );
printf( "whitespace characters: %d\n", spaces );
}

我的 .txt 文件只有 4 个空格和 12 个字母字符,但它给了我 48 个字母字符和 8 个空白字符?为什么会这样? 另外,当我尝试在 printMessage 方法中打印出 int pointeres 时收到警告

最佳答案

没有为任何 int 分配内存,count() 函数只是递增 int 指针而不是 int 值:

++spaces; /* spaces is an int* so this increments the pointer. */

您可以使用 malloc(),但堆栈分配和传递地址会更简单。

int alpha = 0, digit = 0, punct = 0, space = 0;
count(file, &alpha, &digit, &punct, &space);

count() 中:

(*spaces)++;

取消引用 int 用于递增和取消引用打印:

printf( "whitespace characters: %d\n", *spaces);

由于 count() 的调用者不需要 int 的更新值,只需按值传递而完全忘记指针(与 相同) printMessage()).

关于带有 int 指针的转换代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11806503/

相关文章:

c++ - 如何将 QString 转换为 std::string?

c++ - 无法理解工作代码和损坏代码之间的区别

c - 生成有限制的随机数

c - C 中的数组及其指针

java - 如何避免 Spring ConversionService 中的重复转换器?

java - 从 javascript/rhino 调用带有 int 参数的 java 方法

c - 了解空间和时间局部性

c# - 控制电脑风扇速度的开源软件

swift - “Int”无法转换为 'Range<Int>'

tcp - 如何在 Go 编程中将 []byte 转换为 int