在动态分配的空间中如何输入字符串,关于C语言动态给字符串分配内存空间的问题相信很多朋友都不太了解,下面维维带来相关解答,赶紧看看吧。
用malloc来分配内存空间。
即输入几个字节的字符 系统就自动帮我分配几个字节的大小。。
char Str(XXXX)
{
char X=(char*)malloc(sizeof(char)*X)
}
大概就是这么个意思
/* MALLOC.C: This program allocates memory with * malloc, then frees the memory with free. */#include <stdlib.h> /* For _MAX_PATH definition */#include <stdio.h>#include <malloc.h>void main( void ){ char *string; /* Allocate space for a path name */ string = malloc( _MAX_PATH ); if( string == NULL ) printf( "Insufficient memory available\n" ); else { printf( "Memory space allocated for path name\n" ); free( string ); printf( "Memory freed\n" ); }}
Output
Memory space allocated for path nameMemory freed
/#include <stdlib.h>
/* For _MAX_PATH definition */
#include <stdio.h>#include <malloc.h>
void main( void )
{ char *string;
/* Allocate space for a path name */
string = malloc( _MAX_PATH ); if( string == NULL ) //这一句会提示无法从void*转换成char*
printf( "Insufficient memory available\n" );
else { printf( "Memory space allocated for path name\n" );
free( string ); printf( "Memory freed\n" ); }}
void* 可以转的 ,前面加上(char*)