Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

c++ - Passing 2D array of strings to a function

I can initialize a 2D array of strings using the following:

const char * const aListOfStrings[] {"test","test1"};

However, if I want to do the same thing when calling a function, such as:

void function( char const * const aListOfStrings[] ) {}

void CallWithArrayOfStrings()
{
    function( {"test", "test1"} );
}

The compiler politely refuses with the following error:

error: cannot convert '<brace-enclosed initializer list>' to 'char**'

I am able to pass a single string to a function as in:

void function( char const *someString ) {}

void CallWithString()
{
    function( "test" );
}

I seem to understand how to initialize arrays when they are variables, but apparently I don't seem to understand how it works in the context of calling functions. I have always assumed that initializing a variable is the same as initializing a function parameter? Have I been living a lie my whole life? ;)

Thank you

UPATE: Removed C tag. C arrays require an '=' sign before the brace initializer, and the error is different. It appears the problem is very similar however... Also fixed the closing quote.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

const char * const aListOfStrings[] {"test","test1"}; is a shorthand for

const char * const aListOfStrings[2] {"test","test1"};

Size is deduced.

But arguments of signature are fixed (unless template is used), moreover you cannot pass C-array by value, so:

void function(char const * const aListOfStrings[]) is equivalent to

void function(char const * const* aListOfStrings).

To have your syntax, you might use the (strange) syntax

void function(char const * const (&aListOfStrings)[2]);

Demo

or the template version

template <std::size_t N>
void function(char const * const (&aListOfStrings)[N]);

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...