Mail Archives: djgpp/1998/10/13/10:41:34
> I am new in C programming and now learning about pointers.
> Could anyone check for me the codes below for the CORRECT usage of pointers?
>
> int main()
> {
> char crispin[15] , *zunliang[15] , *fauzi[15];
> int cris , *liew , *ogy;
I agree with Yu Jaemin view on declaring pointers.
<snip>
> cris = 14;
> liew = cris;
> ogy = cris;
This is a little incorrect. You are taking that value 14 and assigning
that to cris [declared as an nit]. No problem yet. But then you take
the value [14] of cris and assigned it to liew [declared as an int *].
liew now "points" to address 14. If you want to assign the address of
cris to liew, then use the & operator to get the address, as in ...
liew = &cris;
You can make the assignment ogy = &cris in the same way. But now you
will need to dereference the pointers to get the value [14] back. You
do this with the * operator.
> printf("Info on Crispin: %s and he is %d years old.\n", crispin, cris);
> printf("Info on Liew Zunliang: %s and he is %d years old.\n", zunliang,
> liew);
> printf("Info on Mohd. Fauzi: %s and he is %d years old.\n", fauzi, ogy);
Your printf statements produce that correct output because you use the
%d indicator. This will print a decimal representation regardless if
you pass an int, a short int, a float, a char, or a pointer. Since you
assigned liew and ogy to the value [14] instead of the address of cris,
this outputted correctly.
Using liew and ogy as pointer, you would need to dereference the pointers
to get to the values they point to. Your printf statement should then
look like this...
printf("Info on Crispin: %s and he is %d years old.\n", crispin, cris);
printf("Info on Liew Zunliang: %s and he is %d years old.\n", zunliang, *liew);
printf("Info on Mohd. Fauzi: %s and he is %d years old.\n", fauzi, *ogy);
Notice the dereference operator [*] on liew and ogy.
add these statements to see what is going on with the addresses and values of
cris, liew, and ogy.
printf("addresses: Chris [%p], liew [%p], ogy [%p]\n", &cirs, liew, ogy);
printf("values: Chris [%d], liew [%d], ogy [%d]\n", cris, *liew, *ogy);
printf("base values: Chris [%d], liew [%d], ogy [%d]\n", cris, liew, ogy);
I believe %p will print out an 8 char hexadecimal string represent in an
address.
I hope that helps you out and gives you a better understanding of pointers.
Alan
- Raw text -