我正在编写一个 C 程序,我在其中编写了一个函数来计算函数中的字符数。我必须使用动态内存分配来为数组分配内存,将数组复制到另一个固定大小的数组。我为此编写了以下代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int count_insensitive(char *str, char ch){
int n = 0;
int i;
for (i=0;i<strlen(str);i++){
if (tolower(*(str+i))== tolower(ch)){
n++;
}
}
return n;
}
int main(){
char *a,ch;
int i,n;
n=50;
a = (char*) malloc(sizeof(char) * n);
if (a==NULL){
exit(1);
}
fgets(a,sizeof(a),stdin);
char str[strlen(a)];
strcpy(str,a);
free(a);
char c[] = {'b','H','8','u','$'};
for (i=0;i<5;i++){
ch = c[i];
printf("The character '%c' occurs %d times.\n",c[i],count_insensitive(str,ch));
}
return 0;
}
程序运行但它只接受字符串的前 3 个字符并打印位置。你能帮我看看我做错了什么吗。
最佳答案
来自 fgets()
:
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
其中 num
是传递给 fgets()
的第二个参数。
在您的代码中,您将 sizeof(a)
作为第二个参数传递给 fgets()
:
fgets(a,sizeof(a),stdin);
和a
是char
指针。
指针的大小在 32 位系统上为 4
字节,在 64 位系统上为 8
。
看来你的是 32 位系统,你必须输入超过 4
个字符,这就是为什么 fgets()
只读取第一个 3
给定输入的字符。
由于您正在将 n
个字符的内存分配给指针 a
,因此您应该将 n
作为第二个参数传递给 fgets( )
:
fgets(a, n, stdin);
另外,strlen()
返回一个空终止字符串的长度,不包括终止空字符本身。因此,您应该将 1
添加到 strlen(a)
以确保 str
应该足够长以容纳空终止字符:
char str[strlen(a)+1];
^^
关于通过动态内存分配计算字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613200/