paul
paul

Reputation: 37

Need help understanding char and int pointers

In this code to print the value of int and char pointer variables, why do I access them differently? For the char pointer I write sampleclient but for the int I write *intid. Why does one use * but not the other?

int main()
{
    char client[] = "ABCD";
    int intid = 10;

    samplepass(&client, &intid);

    return 0;   
}

void samplepass(char *sampleclient, int *intid)
{
    printf("%s %d\n", sampleclient, *intid);
}

Upvotes: 3

Views: 164

Answers (3)

ryyker
ryyker

Reputation: 23218

For an output that looks like:

ABCD 10

change your line

from samplepass(&client,&intid);
to samplepass(client,&intid);

Upvotes: 0

John Gowers
John Gowers

Reputation: 2736

In C, you can't pass a string (character array) to a function like printf, so you do the next best thing: pass it its address in memory. The function can then treat the memory address like an array using pointer arithmetic. So the way printf reads strings is by taking in a pointer to the string. Then %s displays the dereferenced string (ABCD here), not the pointer address (which you could get by using %p instead of %s).

The integer problem is more straightforward: the * in *intid means 'get the value stored at this address'. That's why it prints out 10, not the memory address.

The 'correct' format specifier to get a memory address is %p. But you could write:

int main()
{
    char client[] = "ABCD";
    int intid = 10;

    samplepass(&client, &intid);

    return 0;   
}

void samplepass(char *sampleclient, int *intid)
{
    printf("%d %d\n", sampleclient, intid);
}

On my machine, the output was

-2140958000 -2140958004

(and those are the addresses in memory of client and intid). Substituting %p for %d gives nicely formatted pointers with a 0x in front and conforms to the standard, so I'd use that.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

This is because %s format specifier expects a char pointer, while %d expects an integer argument. If you want to see the value of the pointers themselves(i.e. the address they point to) use %p.

Upvotes: 8

Related Questions