如何根据用户输入的长度动态分配 char 变量的数组大小?

How to Dynamically allocate the array size of your char variable based on the length of the user's input?

我需要让用户输入他的名字并将其存储在一个数组中char,这个数组的大小是根据他输入的用户名动态定位的。

这是我的代码:

#include <stdio.h>
void main()
{
    static int size = 5 ;
    printf("please Enter Your First Name..\n");

    char* p = (char*)malloc(size*sizeof(char));

    for(int i = 0 ; i <= sizeof(p) ; i++)
    {
        if(sizeof(p)+1 == size )
        {
            p = (char*)realloc(p,2*size*sizeof(char));
            size = sizeof(p);
        }
        else
        {
            scanf("%c",&p[i]);
        }

    }
    for(int i = 0 ; i <=size ; i++)
    {
        printf("%s",*(p+i));
    }

free(p);

}

我给数组的第一个大小是 5 char,然后如果用户名长度大于这个大小,它会在堆中重新分配两倍大小,

我做了一个条件 if(sizeof(p)+1 == size ) 因为 sizeof(p) = 4 ,所以我需要 5 = 5 所以我把 sizeof(p)+1

但是我的代码不起作用。为什么?

一个常见的错误是使用sizeof(pointer) 来获取它指向的内存的大小。这里有一些示例代码供您尝试。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>             // required header files

#define CHUNK 1  // 8           // amount to allocate each time

int main(void)                  // correct definition
{
    size_t size = CHUNK;        // prefer a larger size than 1
    size_t index = 0;
    int ch;                     // use the right type for getchar()
    char *buffer = malloc(size);
    if(buffer == NULL) {
        // handle erorr
        exit(1);
    }

    printf("Please enter your first name\n");
    while((ch = getchar()) != EOF && ch != '\n') {
        if(index + 2 > size) {       // leave room for NUL
            size += CHUNK;
            char *temp = realloc(buffer, size);
            if(temp == NULL) {
                // handle erorr
                exit(1);
            }
            buffer = temp;
        }
        buffer[index] = ch;
        index++;
    }

    buffer[index] = 0;               // terminate the string
    printf("Your name is '%s'\n", buffer);
    printf("string length is %zu\n", strlen(buffer));
    printf("buffer size   is %zu\n", size);

    free(buffer);
    return 0;
}

计划session:

Please enter your first name
Weather
Your name is 'Weather'
string length is 7
buffer size   is 8

我宁愿使用更大的缓冲区大小,因为这样对系统的压力更小,而且因为分配的内存可能无论如何都使用最小大小。当我设置

#define CHUNK 8

session 是

Please enter your first name
Wilhelmina
Your name is 'Wilhelmina'
string length is 10
buffer size   is 16