简体   繁体   English

在运行时将内存分配给字符串

[英]Allocating Memory to String at runtime

I am writing a program to count the occurrence of '2' followed by '1' in a sting. 我正在编写一个程序来计算字符串中出现“ 2”后跟“ 1”的次数。 I dynamically allocated string 我动态分配了字符串

Code is: 代码是:

#include <stdio.h>
#include<stdlib.h>

    int penalty_shoot(char* s){
        int count=0,i=0;
        while(s[i]!='\0'){
           if(s[i]=='2')
                if(s[i+1]=='1')
                    count++;
        i++;
        }
        return count;
    }

    int main() {
        int t;
        int i=0;
        scanf("%d",&t);           //t is for number of test cases.
        while(t--){
            char *str, c;
            str = (char*)malloc(1*sizeof(char));
            while(c = getc(stdin),c!='\n')
            {
                str[i] = c;
                i++;
                str=realloc(str,i*sizeof(char));
            }
            str[i] ='\0';
            printf("%s\n",str);
            printf("%d\n",penalty_shoot(str));

            free(str);
            str=NULL;
            i=0;
        }
        return 0;
    }

Input is : 输入为:

3
101201212110
10101
2120

I am facing 2 problems: 我面临2个问题:

1) I feel the dynamic allocation is not working fine.I wrote the code for dynamic allocation seeing various codes on stackoverflow . 1)我觉得动态分配不能正常工作。我在stackoverflow上看到了各种代码,为动态分配编写了代码。 (Can anyone suggest some changes.) (任何人都可以提出一些建议。)

2) The code isn't reading '2120' as the 3rd input. 2)代码没有读取“ 2120”作为第三个输入。 (why is it so ?) (为什么会这样?)

Three errors: 三个错误:

  1. Not checking for EOF : 不检查EOF

    Change while(c = getc(stdin),c!='\\n') to while(c=getc(stdin),c!='\\n'&&c!=EOF) while(c = getc(stdin),c!='\\n')更改为while(c=getc(stdin),c!='\\n'&&c!=EOF)

  2. Reallocating with the wrong number of bytes: 用错误的字节数重新分配:

    Change str=realloc(str,i*sizeof(char)); 更改str=realloc(str,i*sizeof(char)); to str=realloc(str,(i+1)*sizeof(char)); str=realloc(str,(i+1)*sizeof(char));

    After taking one character input we increment i ( i++ ), so the next character will be stored at the ith position. 输入一个字符后,我们将ii++ )递增,因此下一个字符将存储在第ith位置。 Now, in order to store the character at ith position, the length of the character array must be i+1 . 现在,为了将字符存储在ith位置,字符数组的长度必须为i+1 So, we realloc with i+1 . 因此,我们用i+1 realloc

    Just for the sake of brevity, as suggested by Basile, you might as well do this: 出于简洁起见,正如Basile建议的那样,您也可以这样做:

    Change str=realloc(str,(i+1)*sizeof(char)); 更改str=realloc(str,(i+1)*sizeof(char)); to str=realloc(str,i+1); str=realloc(str,i+1);

    Why? 为什么? Because sizeof char is 1 byte 因为sizeof char1个字节

  3. Not consuming the \\n after inputting t : 输入t后不消耗\\n

    Change scanf("%d",&t); 更改scanf("%d",&t); to scanf("%d ",&t); scanf("%d ",&t); or scanf("%d\\n",&t); scanf("%d\\n",&t);

    scanf("%d ",&t); or scanf("%d\\n",&t); scanf("%d\\n",&t); .

    Either of them works. 他们中的任何一个都可以。 Why, you ask? 你为什么问? Read this explanation taken from another SO answer here : 在这里阅读从另一个SO答案中获得的解释:

    An \\n - or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input. 格式字符串中的\\n或任何空白字符-在输入中会消耗整个(可能为空)空白字符序列。 So the scanf only returns when it encounters the next non-whitespace character, or the end of the input stream. 因此,scanf仅在遇到下一个非空白字符或输入流的结尾时才返回。

Tested here . 在这里测试。

you can use scanf("%d ", &t); 您可以使用scanf("%d ", &t); when user input to test then just before second while loop, which condition should be c != '\\n' write c = getchar(); 当用户输入要进行测试的代码时,恰好在第二次while循环之前,该条件应为c != '\\n'编写c = getchar(); and then make sure you create a char variable, i called mine clear, that receives 0 so when you loop after initiating your string you write c = clear; 然后确保您创建一个char变量,我称为mine clear,该变量接收0,因此在启动字符串后循环时,您将代码写为c = clear; and under it c = getchar() again. 在其下c = getchar()再次。 and when you use realloc make sure you make it bigger by (i+1) since char is only the size of 1 byte. 当您使用realloc时,请确保将其增大(i + 1),因为char的大小仅为1个字节。

we create the clear variable in order to clear the buffer. 我们创建clear变量以清除缓冲区。

it worked for me. 它为我工作。 make sure you insert the string all at once. 确保一次插入所有字符串。

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

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