【问题标题】:I'm trying to create a string with n characters by allocating memories with malloc, but I have a problem我正在尝试通过使用 malloc 分配内存来创建一个包含 n 个字符的字符串,但我遇到了问题
【发布时间】:2021-05-01 03:26:03
【问题描述】:

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        int n;
        printf("Length? ");
        scanf("%d", &n);
        getchar();
        char* str = (char*)malloc(sizeof(char) * (n+1));
        fgets(str,sizeof(str),stdin);
        for (int i = 0; i < n; i++)
            printf("%c\n", str[i]);
        free(str);
    }

这样处理结果!

长度? 5
abcde
一个
b
c

?

(我想上传结果图片,但因为没有10个声望而被拒绝)

我不明白为什么“d”和“e”不会出现在结果中。 我的代码有什么问题??

【问题讨论】:

    标签: string malloc fgets


    【解决方案1】:

    (欢迎使用 stackoverflow :)(更新 #1)

    str指向 char 的指针,而不是 字符数组,因此 sizeof(str) 在 64 位上始终为 8,在 32 位上始终为 4位机,不管你分配了多少空间。

    演示(仅当 static_assert(X) 中的 X 成立时编译成功):

    #include <assert.h>
    #include <stdlib.h>
    
    int main(void){
    
      // Pointer to char
      char *str=(char*)malloc(1024);
    
    #if defined _WIN64 || defined __x86_64__ || defined _____LP64_____
      static_assert(sizeof(str)==8);
    #else
      static_assert(sizeof(str)==4);
    #endif
    
      free(str);
    
      // Character array
      char arr[1024];
      static_assert(sizeof(arr)==1024);
    
      return 0;
    
    }
    

    fgets(char *str, int num, FILE *stream) 一直读取直到 (num-1) 个字符被读取

    请不要fgets(str,sizeof(str),stdin)fgets(str,n+1,stdin)

    固定版本:

    #include <assert.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
      int n=0;
      printf("Length? ");
      scanf("%d",&n);
      getchar();
      char *str=(char*)calloc((n+1),sizeof(char));
      static_assert(
        sizeof(str)==sizeof(char*) && (
          sizeof(str)==4 || // 32-bit machine
          sizeof(str)==8    // 64-bit machine
        )
      );
      fgets(str,n+1,stdin);
      for(int i=0;i<n;++i)
        printf("%c\n",str[i]);
      free(str);
      str=NULL;
    }
    
    Length? 5
    abcde
    a
    b
    c
    d
    e
    

    【讨论】:

    • 非常感谢您的详细解释。它帮助很大(:
    • @DanielCha 你可能想accept the answer
    猜你喜欢
    • 2014-08-10
    • 2018-03-12
    • 2011-02-17
    • 1970-01-01
    • 2014-12-05
    • 2021-06-11
    • 2016-07-28
    • 2021-11-12
    相关资源
    最近更新 更多