【发布时间】:2018-04-08 07:54:31
【问题描述】:
在下面的代码中,我想用一个临时的指针数组调用函数f() 或f2(),如第 33 行和第 39 行...
#include <stdio.h>
void f( const char** const p, size_t num )
{
size_t i;
for ( i = 0; i < num; ++i )
{
printf( "%s\n", p[ i ] );
}
}
void f2( const char* const p[2] )
{
size_t i;
for ( i = 0; i < 2; ++i )
{
printf( "%s\n", p[ i ] );
}
}
void withPtrArray()
{
const char* tmp[] = { "hello", "world" };
const char** p;
// This compiles/runs fine:
f( tmp, sizeof tmp / sizeof( const char* ) );
// This also compiles/runs fine:
f( ( p = tmp ), 2 );
// This does not compile - I'm not clear why.
f( ( { "hello", "world" } ), 2 );
// My last hope: I thought a function that explicitly took a pointer array:
// This works...
f2( tmp );
// ...but this does not:
f2( { "hello", "world" } );
}
void g( const char* const p )
{
printf( "%s\n", p );
}
// Analog to f2()
void g2( const char p[12] )
{
printf( "%s\n", p );
}
// These analogs with an array of chars work fine.
void withPtr()
{
const char tmp[] = "hello world";
const char* p = tmp;
g( tmp );
g( ( p = tmp ) );
g( ( "hello world" ) );
g2( tmp );
g2( "hello world" );
}
int main( int argc, char* argv[] )
{
withPtrArray();
withPtr();
return 0;
}
...但是那些行编译失败...
prog.c: In function ‘withPtrArray’:
prog.c:33:17: warning: left-hand operand of comma expression has no effect [-Wunused-value]
f( ( { "hello", "world" } ), 2 );
^
prog.c:33:27: error: expected ‘;’ before ‘}’ token
f( ( { "hello", "world" } ), 2 );
^
prog.c:33:6: warning: passing argument 1 of ‘f’ from incompatible pointer type [-Wincompatible-pointer-types]
f( ( { "hello", "world" } ), 2 );
^
prog.c:3:6: note: expected ‘const char ** const’ but argument is of type ‘char *’
void f( const char** const p, size_t num )
^
prog.c:39:7: error: expected expression before ‘{’ token
f2( { "hello", "world" } );
^
我从 C 迁移到 C++ 已经有几年了,但我不认为这是 C 和 C++ 之间语法差异的问题。
是否有允许将临时指针数组传递给函数的 C 语法?
【问题讨论】:
-
@EugeneSh。 - 美丽的!
f( (const char*[]){ "hello", "world" }, 2 );是需要的秘方。如果您想要积分,您应该发布作为答案。谢谢!
标签: c arrays pointers temporary