Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie with pointers

Status
Not open for further replies.

Sen7inel

IS-IT--Management
Feb 14, 2001
90
0
0
FI
Ok,

I'm trying to learn the basics of C here. What have I misunderstood about pointers, as I thought this would work:

[tt]
#include "stdafx.h"

void main()
{
char* duh = "Foo";
printf("%s", *duh);
}
[/tt]

printf("%s", duh); works fine. Why? Shouldn't it print out the memory address?

(the only stupid question is the one that is not asked =))
 
OK - A pointer is an area of memory that is used to contain the address of another area of memory - hence the name pointer.

In the case you cite when you put the %s parameter in the printf string then the printf function is expecting the address of a string and this is what your pointer contains so the printf function uses that address to extract the string and print it. The following should shed more light on this...

char* duh = "Foo";
printf("The pointer at %X contains the address %X which is the start of the string %s",&duh,duh,duh);

Notice that &duh means the address of duh,the first duh means the contents of duh expressed in hexadecimal and the last duh means the contents of duh expressed as a string pointer.

Cheers - Gavin
 
hi.. the syntax for prantf requires that you give out the address of the location pointed by the pointer.

here is an example:


Code:
char buff[20] = "First line";
char buff1[ ] = "Second line";
char *buff2 = "Third line";

To pass them on as parameters in your printf, you need to specify the address from where you want the print to happen.

printf ("%s", buff);
printf ("%s", buff1);
printf ("%s", buff2);

Note: If you use arrays, the following is implicitly meant and holds true ..

buff 'means' &buff[0];
buff1 'means' &buff1[0];
and so on .... 

that is why the above printf statements are "identical" to the following:

printf ("%s", &buff[0]);
printf ("%s", &buff1[0]);

hope this helps

BR: nagi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top