1

How can I pass a char* array as a parameter, without creating one and initializing it?

This code works (creating an initializing one):

char *messages[] = {"Zero", "One", "Two", "Three"};
printf("%s", messages[1]);

But it wont work if you pass it like so:

#include <stdio.h>

void printElement1(char *messages[]) {
    printf("%s", messages[1]);
}

int main(void) {

    printElement1({"Zero", "One", "Two", "Three"});

    return 1;
}

I cannot use a va_list, the function takes a char* array and that's that.

1 Answer 1

6

You're just missing the type for your compound literal. Change that line to:

printElement1((char *[]){"Zero", "One", "Two", "Three"});

and it will work fine.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! That's incredible, I had no idea you could type cast like this.
It's not a typecast, it's a compound literal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.