:: Re: [DNG] Making sense of C pointer…
Top Pagina
Delete this message
Reply to this message
Auteur: KatolaZ
Datum:  
Aan: Emiliano Marini
CC: dng
Onderwerp: Re: [DNG] Making sense of C pointer syntax.
On Thu, Mar 31, 2016 at 08:38:26AM -0300, Emiliano Marini wrote:
> +1
>
> Besides, * and [] are interchangeable. You can define a string as an array
> and use it later as a pointer:
>
> char s[] = "hola";
> char x = s[1];     // Here x = 'o'
> char y = *(s+2);   // Here y = 'l'

>
> And vice versa:
>
> char *s = "hola";
> char x = s[0];     // Here x = 'h'
> char y = *(s+3);   // Here y = 'a'

>


Just to be pedantic here, "[]" is just syntactic sugar around the
dereference operator "*". And in fact "[]" did not even exist in the
first versions of proto-C. Obviously, "[]" is syntactic sugar around
unary "*" for *any* kind of pointer, not just for strings.

Also, initialisation of char* and char[] by means of

char s[] = "hello";

is syntactic sugar around the generic initialiser:

type p = {...};

which allows to initialise arrays and compound variables (structs and
unions) as well. But be careful with statically initialised strings,
since they are effectively constant char pointers (they are stored in
the current stack frame, not in the heap, and the address stored in
such variables cannot be modified, AFAIR).

My2Cents

KatolaZ

--
[ Enzo Nicosia aka KatolaZ --- GLUG Catania -- Freaknet Medialab ]
[ me [at] katolaz.homeunix.net -- http://katolaz.homeunix.net -- ]
[ GNU/Linux User:#325780/ICQ UIN: #258332181/GPG key ID 0B5F062F ]
[ Fingerprint: 8E59 D6AA 445E FDB4 A153 3D5A 5F20 B3AE 0B5F 062F ]