[英]Can a temporary array of pointer be passed to a function in C?
在下面的代码中,我想使用临时指针数组调用函数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语言语法允许将指针的临时数组传递给函数?
f( ( { "hello", "world" } ), 2 )
是:函数的参数必须是表达式。 但是,其他表达式的括号列表本身不是表达式。
也许您错误地认为{ "hello", "world" }
是一个表达式,其类型可能是“ 2个字符数组的数组”。 但这不是事实。 您可能已经注意到{ "hello" };
也不是有效的代码:每个表达式都可以通过放置;
转换为语句;
在此之后,因此{"hello"}
不能是表达式。
以下代码也不起作用:
char *c[2];
c = { "hello", "world" };
甚至:
int y;
y = { 5 };
在这两种情况下,赋值运算符都必须后面跟一个表达式。 但是没有表达式的语法由花括号括起来。
支撑列表只能作为声明的初始化程序或以复合文字形式出现。 大括号表示存在初始化器列表。
声明的解剖结构是类型名和声明符,后跟=
符号(这不是赋值运算符,因为它不是表达式),后跟初始化器。 初始值设定项可以是表达式,也可以是初始设定值列表。 这种声明的含义是,将每个初始化程序都用作声明中声明的对象之一的初始值。
在您的代码中,您可以使用复合文字:
f( (const char *[2]){ "hello", "world" }, 2 );
复合文字的剖析在于,它是用于为类型名称的初始化对象提供类型名称的语法。 它不是将强制转换运算符应用于某种表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.