简体   繁体   English

通过动态内存分配计算字符串中的字符

[英]Counting characters in a string by dynamic memory allocation

I am writing a C program where I write a function to count the number of character in a function. 我正在编写一个C程序,其中编写了一个函数以计算函数中字符的数量。 I have to use a dynamic memory allocation to allocate memory for an array take the array and copy it to another with fixed size. 我必须使用动态内存分配为一个数组分配内存,然后将该数组复制到固定大小的另一个数组中。 I have wrote the following code for it: 我为此编写了以下代码:

#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;
}

The program runs but it take only the first 3 characters of a string and prints the position. 该程序会运行,但只使用字符串的前3个字符并打印位置。 Can you help me what I am doing wrong. 您能帮我做错什么吗?

From fgets() : 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. 从流中读取字符,并将它们作为C字符串存储到str中,直到已读取(num-1)个字符或到达换行符或到达文件末尾为止,以先发生的为准。

where num is the second argument passed to fgets() . 其中num是传递给fgets()的第二个参数。

In your code, you are passing sizeof(a) as second argument to fgets() : 在您的代码中,您将sizeof(a)作为第二个参数传递给fgets()

fgets(a,sizeof(a),stdin);

and a is char pointer. achar指针。

The size of pointer will be 4 byte on a 32-bit system and 8 on a 64-bit system. 指针的大小在32位系统上为4字节,在64位系统上为8字节。

Seems that yours is 32-bit system and you must be giving input of more that 4 characters, that's why fgets() is reading only first 3 characters of the given input. 似乎您的系统是32位系统,并且您必须输入的字符数必须超过4 ,这就是为什么fgets()仅读取给定输入的前3字符的原因。

Since, you are allocating memory of n characters to pointer a , you should pass n as second argument to fgets() : 由于要为指针a分配n字符的内存,因此应将n作为第二个参数传递给fgets()

fgets(a, n, stdin);

Also, strlen() returns length of a null terminated string without including the terminating null character itself. 同样, strlen()返回以null终止的字符串的长度,而不包括终止null字符本身。 So, you should add 1 to strlen(a) to ensure that str should be long enough to accommodate null terminating character: 因此,应在strlen(a)上加1 ,以确保str足够长以容纳空终止符:

char str[strlen(a)+1];
                  ^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM