Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dubious syntax to access array content

Tags:

arrays

c

syntax

In some legacy code I have to maintain, & operators are put in front of arrays names whenever the arrays are to be passed as (void *) arguments

Here is a simple example :

char val = 42;
char tab[10];
memcpy(&tab, &val, 1);

It compiles with gcc or clang without errors or warnings. It also gives the expected result.

Is this syntax legal ?

Why does this works ?

Notes : I usually use one of the following syntax :

memcpy(tab, &val, 1);
memcpy(&tab[0], &val, 1);

Epilog :

As an additional test, I used a function taking a (char*) argument instead of (void*)

I get the following warning if I try to compile with clang :

warning: incompatible pointer types passing 'char (*)[10]' to parameter of type 'char *' [-Wincompatible-pointer-types]

Edit 1 : In the original example tab was given with a size of 1 element

I just changed the size to 10 for the sake of generality.

Edit 2 : As mentionned in the answers, memcpy takes (void*) and not (char*)

like image 677
Flibustier Avatar asked Dec 25 '22 19:12

Flibustier


1 Answers

memcpy's parameters are of type void*, not char*. Any argument of pointer type (excluding function pointers) is implicitly converted to void*. This is a special-case rule that applies only to void*.

Given the declaration

char tab[1];

either tab or &tab is valid as an argument to memcpy. They evaluate to pointers of different types (char* and char (*)[1]), but both pointing to the same memory location; converting either to void* yields the same value.

For a function that actually requires a char* argument, only tab is valid; &tab is of the wrong type. (For a variadic function like printf or scanf, the compiler may not be able to detect the type mismatch.)

like image 133
Keith Thompson Avatar answered Dec 30 '22 11:12

Keith Thompson