我试图通过使用 malloc 分配内存来创建一个包含 n 个字符的字符串,但我遇到了问题

I'm trying to create a string with n characters by allocating memories with malloc, but I have a problem


    #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' 不会显示在结果中。 我的代码有什么问题??

(欢迎来到 Whosebug :)(更新 #1)

str 是指向 char 的 指针而不是 字符数组 因此 sizeof(str) 总是 8 在 64 位机器上或 4 在 32 位机器上,无论你分配了多少 space。

Demo(只有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,n+1,stdin)

而不是 fgets(str,sizeof(str),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