繁体   English   中英

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

[英]Allocating Memory to String at runtime

我正在编写一个程序来计算字符串中出现“ 2”后跟“ 1”的次数。 我动态分配了字符串

代码是:

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

输入为:

3
101201212110
10101
2120

我面临2个问题:

1)我觉得动态分配不能正常工作。我在stackoverflow上看到了各种代码,为动态分配编写了代码。 (任何人都可以提出一些建议。)

2)代码没有读取“ 2120”作为第三个输入。 (为什么会这样?)

三个错误:

  1. 不检查EOF

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

  2. 用错误的字节数重新分配:

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

    输入一个字符后,我们将ii++ )递增,因此下一个字符将存储在第ith位置。 现在,为了将字符存储在ith位置,字符数组的长度必须为i+1 因此,我们用i+1 realloc

    出于简洁起见,正如Basile建议的那样,您也可以这样做:

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

    为什么? 因为sizeof char1个字节

  3. 输入t后不消耗\\n

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

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

    他们中的任何一个都可以。 你为什么问? 在这里阅读从另一个SO答案中获得的解释:

    格式字符串中的\\n或任何空白字符-在输入中会消耗整个(可能为空)空白字符序列。 因此,scanf仅在遇到下一个非空白字符或输入流的结尾时才返回。

在这里测试。

您可以使用scanf("%d ", &t); 当用户输入要进行测试的代码时,恰好在第二次while循环之前,该条件应为c != '\\n'编写c = getchar(); 然后确保您创建一个char变量,我称为mine clear,该变量接收0,因此在启动字符串后循环时,您将代码写为c = clear; 在其下c = getchar()再次。 当您使用realloc时,请确保将其增大(i + 1),因为char的大小仅为1个字节。

我们创建clear变量以清除缓冲区。

它为我工作。 确保一次插入所有字符串。

暂无
暂无

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

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