【问题标题】:1st character of pointer string not printed未打印指针字符串的第一个字符
【发布时间】:2018-07-21 17:24:19
【问题描述】:

我正在尝试为长度未知的字符串分配动态内存(我正在尝试模拟编译问题),但是当我这样做时,我的 printf 不会从第二次执行中打印第一个字符。我正在使用 gcc 5.something。我附上了输出的屏幕截图。

   #include<stdio.h>
   #include<stdlib.h>
   #include<string.h>
   void main (){


    //VARIABELS

        //Input bitstream as a string
        char *stringInput;

        //No of inputs
        int dataCount;

        //memory size to allocate to array
        int dataSize; 

        //FILE pointer
        FILE *fptr;

        //Loop count
        int i;

        //Binary declarations
        long num, decimal_num, remainder, base = 1, binary = 0, noOf1 = 0;



        //MEMORY ALLOCATION

        //Enter N
        printf("Enter N (the number of inputs):\n");
        scanf("%d",&dataCount);

        //+1 for comma (,) characters
        dataSize = ((sizeof(int)+1)* dataCount);

        //Initialize pointer allocated memory
        stringInput = malloc(dataSize);

        if (!stringInput)
        { 
            perror("Error allocating memory");
            abort();
        }

        memset(stringInput, 0, dataSize);
        //Scan the numbers + TEST
        scanf("%s",stringInput);

        //Initialize file pointer
        fptr = fopen("inputString.txt","w"); 
        fprintf(fptr,"%s",stringInput);

        free(stringInput);



        //DECIMAL CONVERSION
        while (num > 0){
            remainder = num % 2;

            //Calc no of 1's
            if (remainder == 1)
                noOf1++;

            //Conversion
            binary = binary + remainder * base;
            num = num / 2;
            base = base * 10;
        }



    }

【问题讨论】:

  • sizeof int 为您提供存储int 所需的字节数。这与将此值写为十进制数字所需的字符数无关。
  • 请改用sizeof(char),或者直接省略它,因为sizeof(char) 始终为1。空终止符需要+1。并且您应该将dataCount 作为参数传递给scanf(),这样如果用户键入的字符数超过dataCount,它就不会溢出stringInputscanf("%*s", dataCount, stringInput);
  • @FelixPalmen 是的,我需要将输入作为字符串,但字符串将包含整数和逗号且没有空格,最大 50 个整数,但由于输入是字符串形式,我们正在处理字符( 1 字节)和整数为 8 字节(x64 环境),所以我的最大数组大小 =(50 个整数 *8+49 逗号 +1(对于 \0))= 450 哦 gg 我解决了我自己的问题 lol a lil 1 有巨大的1 领先
  • 请勿发布屏幕截图。而是将实际文本复制并粘贴到您的问题中

标签: c string dynamic initialization malloc


【解决方案1】:

改变这个:

dataSize = ((sizeof(int)+1)* dataCount);

到这里:

dataSize = ((sizeof(char) + 1) * (dataCount + 1));

因为你想存储一个字符串,而不是一个数字。

注意我最后使用的+1,它是字符串NULL终止符。


PS:What should main() return in C and C++?int.

【讨论】:

  • 假设每个“数字”只有一个十进制数字。哦,+1 在这里的每一项都添加了一个。老实说,我不懂 OPs 代码,但它会对未初始化的 num 进行一些计算。
  • sizeof(char) 是一个字符的大小,代表整数的字符序列的大小是它的倍数。 ',' 的大小也是sizeof(char) 这次实际上只有一次。在这里使用+1 假设一个字符是一个字节。我错过了什么吗?
  • 对不起,我的评论错了,但确实增加了两个字节。再次查看 OP 的代码,这看起来不像问题的实际根源。使用未初始化的变量很糟糕,使用scanf("%s", ...) 很糟糕,这段代码中的任何地方都可能发生糟糕的事情。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2021-03-27
  • 2011-09-17
  • 2017-07-19
  • 1970-01-01
  • 2013-05-31
  • 2013-02-08
  • 2021-05-11
相关资源
最近更新 更多