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



我需要让用户输入他的名字并将其存储在数组中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);
}

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

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 namen");
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 %zun", strlen(buffer));
printf("buffer size   is %zun", size);
free(buffer);
return 0;
}

计划会议:

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

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

#define CHUNK 8

会话是

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