Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I cast arrays to pointers when passing them to variadic functions like printf?

Tags:

c++

c

printf

Can I pass an array to printf directly:

char text[1024] = "text";
printf("%s", text);

Or should I explicitly cast it to a char pointer:

char text[1024] = "text";
printf("%s", (char*) text);

I'm asking because I thought maybe it copies the array elements directly into the va_list instead of putting just a pointer to the first element.

like image 939
sashoalm Avatar asked Dec 13 '22 03:12

sashoalm


2 Answers

Yes, you can pass an array directly. Exactly, name of array represents address of the array which makes no difference with char *.

like image 73
Summer_More_More_Tea Avatar answered Dec 31 '22 01:12

Summer_More_More_Tea


(char*)text and text hardly make any difference in this example! Base address of an array decays into a pointer when passed as a function argument.

In fact, even if text was not a char array, still it would hardly make any difference to printf because it is a variable argument function

int printf(const char *format, ...);

and all it cares is about the first argument. Logic might go wrong but printf doesn't care!

like image 40
Pavan Manjunath Avatar answered Dec 31 '22 01:12

Pavan Manjunath