以下程序,会存在什么问题?如果有问题,请更正. void GetMemory(char *p) { p = (char *)malloc(100); } void Test(char *s) { char *str = NULL; GetMemory(str); strcpy(str, s); printf(str); }
时间: 2024-03-06 08:50:04 浏览: 81
以上程序存在问题,因为在GetMemory函数中分配的内存地址被赋值给了GetMemory函数中的局部变量p,而不是Test函数中的指针str。因此,在Test函数中使用str指针时,它指向的仍然是NULL,从而导致程序运行时出现段错误。
为了解决以上问题,可以将GetMemory函数修改为传入指针的地址,即将char *p改为char **p。这样,在GetMemory函数中分配的内存地址就可以通过指针的指针修改Test函数中的指针str所指向的地址。
修改后的代码如下:
```c++
void GetMemory(char **p) {
*p = (char *)malloc(100);
}
void Test(char *s) {
char *str = NULL;
GetMemory(&str);
strcpy(str, s);
printf("%s", str);
}
```
这样就可以正确地分配内存并使用指针str了。
相关问题
8.void getmemory(char *p) { p=(char *) malloc(100); strcpy(p,“hello world”); } int main( ) {c char *str=NULL; getmemory(str); printf(“%s/n”,str); free(str); return 0;
这段代码的问题在于:在函数getmemory中,参数p是一个指向char类型的指针,但在函数中对p进行了赋值操作,即将p指向了一个malloc分配的内存空间,但这个赋值操作只在函数内部生效,函数外部的指针str并没有指向新分配的内存空间,而是仍然为NULL,所以在主函数中打印str时会出现问题。正确的做法是将参数p改为指向指针的指针,这样在函数中对*p进行操作时,会对主函数中传入的指针进行操作,从而使主函数中的指针指向新分配的内存空间。修改后的代码如下:
```c
void getmemory(char **p) {
*p = (char *) malloc(100);
strcpy(*p, "hello world");
}
int main() {
char *str = NULL;
getmemory(&str);
printf("%s/n", str);
free(str);
return 0;
}
```
以下代码有问题吗?如果有,是什么问题,怎么改正。 void getmemory( char *p ) { p = (char *) malloc( 100 ); } void test( void ) { char *str = null; getmemory( str ); strcpy( str, "hello world" ); puts( str ); }
有问题。在getmemory函数中,为指针分配了内存空间,但是分配的空间地址并没有传递出去,因此在调用test函数时,str指针是未初始化的,并不指向任何内存空间。修改方法是,在getmemory函数中改为传递指针的地址,并在test函数中对指针进行解引用,如下所示:
void getmemory( char **p ) {
*p = (char *) malloc( 100 );
}
void test( void ) {
char *str = NULL;
getmemory( &str );
strcpy( str, "hello world" );
puts( str );
}
阅读全文
相关推荐


















