int i = 0 ;
static int a[] = { 0, 1, 2, 3, 4 } ;
void print_book ( struct t_book *b )
{
printf("The title is: %s\n", (*b).title ) ;
printf("The author is: %s\n", b->author ) ;
printf("The price is: %lf\n", b->value );
}
The "->" operator is dereferencing + selection (follow a pointer to a structure and take just one field of the structure)
char c1, c2, *p ;
p=&c ; /* p will point to the location of c */
c='a' ; /* c will take the value 'a' */
putchar(*p) ; /* the content of the location pointed by p will be printed */
p++ ; /* allowed but wrong in this context */
(*p)++ ; /* the content of the location pointed by p will be incremented*/
putchar(*p) ; /* see above */
c1 = *p ; /* the content of the location pointed by p will be copied in c1 */
c = p ; /* not allowed - type mismatch */
p = *c ; /* not allowed */
p = &c1 ; /* p will point to the location of c1 */
Observation 1:
by definition, the name of an array is the address of the first element
p = &(carray[0]) ; <=> p = carray ;
Observation 2:
p + i points to the i-th element of the array: p = p + i*sizeof(data type)
p + i will point
Draw a picture showing the situation in the memory after the execution of the following instructions. The picture should include all variables. You can assume that sizeof(int) = 2, sizeof(char) = 1 (in bytes).
char carray[ 16 ] = { "this is a string"} ;
char *p1 ;
int iarray[ 20 ], *p2 ;
p1 = carray ; p2 = iarray ;
p1 += 2 ;
*p1++ = 'a' ;
*p1 = 't' ;
*p2 = 5 ;
double *dp, atof (char *), d, *x, *y ;
&(x+y) NO!
&PI NO!
*dp = *dp + 10 ; YES!
*dp = *dp + 1; YES!
*dp += 1 ; YES!
++ *dp ; YES!
(*dp)++ ; YES! We need (): p(*)=p(++) and left ->right
x = y ; YES!
*x = *y ; YES!
*x = &y NO!
x = &d ; YES!
d = *x ; YES!
d = &y ; NO!
*x = d + *y ; YES!
int a[10], *pa ;
pa = &a[0] or pa = a ;
*(pa+1) = 0 ; a[1] = 0 ;
*(pa+i) = 1 ; a[i] = 0 ;
int *pa ;
int a[10] ;
pa = a ;
pa[i] = 3 ; /* It's ok ! A pointer is used with an index !!!*/
*(a+2) = 5 ; /* It's ok ! An array is used as a pointer */
a++ ; /* NO! The name of an array is the address of the first element. I cannot change this value! */
Obs: like any character string in C, both strings are terminated with '\0'.
Solution 1: