1 c pointers global-variables local void-pointers
我想使用本地指针指向全局字符串.指针是本地指针,字符串是全局的.当我运行此代码时,将本地指针传递给函数"myfun"时,指针不会改变,即其指向地址不会改变.打印的值为"NULL".
谁能告诉我为什么这对gcc不起作用?
#include <stdio.h>
char *str[] = { "String #1", "Another string" };
void myfun( void * p, int i )
{
p = ( void * ) &str[ i ][ 0 ];
}
int main( void )
{
void * ptr1, * ptr2;
myfun( ptr1, 0 );
myfun( ptr2, 1 );
printf( "%s\n%s\n", ptr1, ptr2 );
}
Run Code Online (Sandbox Code Playgroud)
您正在按值传递指针myfun
.分配给该值p
在myfun
因此不返回给调用者.您需要将指针传递给指针:
void myfun( void ** p, int i )
{
*p = ( void * ) &str[ i ][ 0 ];
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
myfun( &ptr1, 0 );
Run Code Online (Sandbox Code Playgroud)
实际上你可以myfun
像这样写:
void myfun( void ** p, int i )
{
*p = str[i];
}
Run Code Online (Sandbox Code Playgroud)
事实上,只返回void*
函数返回值是最简单的:
void *myfun( int i )
{
return str[i];
}
Run Code Online (Sandbox Code Playgroud)