首 页最新软件下载排行文章资讯投稿发布下载专题
维维下载站
您的位置:首页编程开发网络编程编程其它 → 关于C语言动态给字符串分配内存空间问题

关于C语言动态给字符串分配内存空间问题

来源:维维整理 发布时间:2010-3-15 14:40:00 人气:

在动态分配的空间中如何输入字符串,关于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*)

相关下载
栏目导航
本类热门阅览