我想用一个本地指针指向一个全局字符串。指针是局部指针,字符串是全局的。当我运行这段代码将本地指针传递给函数“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 );
}
最佳答案
您正在按值将指针传递给 myfun
。因此,您在 myfun
中分配给 p
的值不会返回给调用者。您需要将指针传递给指针:
void myfun( void ** p, int i )
{
*p = ( void * ) &str[ i ][ 0 ];
}
然后这样调用它:
myfun( &ptr1, 0 );
事实上你可以这样写myfun
:
void myfun( void ** p, int i )
{
*p = str[i];
}
事实上,返回 void*
作为函数返回值是最简单的:
void *myfun( int i )
{
return str[i];
}
关于c - 指向全局函数的局部指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10741985/