以下程序,会存在什么问题?如果有问题,请更正. 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 17:50:04 浏览: 30
以上程序存在问题,因为在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了。
相关问题
以下代码有问题吗?如果有,是什么问题,怎么改正。 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 );
}
void Test(void) char *str = NUL:str=GetMemory(printf(str). 请间运行 Test 函数会有什么样的结果?
该函数存在语法错误,正确的语法应该是:
```
void Test(void) {
char *str = NULL;
str = GetMemory();
printf("%s", str);
free(str);
}
```
在上面的函数中,GetMemory 函数分配了一段内存空间并返回了指向该内存空间的指针,然后通过 printf 函数输出了该指针所指向的字符串,最后通过 free 函数释放了该内存空间。
然而,在 GetMemory 函数的原始实现中,没有向分配的内存空间中写入任何内容,因此在 printf 函数中输出该指针所指向的字符串时,会输出一些随机字符,而不是预期中的 "hello world" 字符串。此外,函数中的语法错误也会导致编译失败。