Home > Software engineering >  Pointers in a function C language
Pointers in a function C language

Time:08-20

Hello i am new to C language and trying to understand pointers.

Doing some examples i stumbled with this function and im not completely sure what it is about.

void dump(void *p, int n)
{
    unsigned char *p1 = p;
    while (n--)
    {
        printf("%p - x\n", p1, *p1);
        p1  ;
    }
}

I dont understand the p in unsigned char *p1 = p; there is no other use for it in the function. I also dont quite understand the p1 in printf("%p - x\n", p1, *p1);, is it the actual value of the *p1 pointer?

Can anyone explain this topics to me? I'll be very grateful.

In the example it shows me that when a i run with this main()

int main(void)
{
    int i = 10000;
    dump(&i, sizeof(i));
    return 0;
}

the output is

0x7ffd7e787e74 - 10
0x7ffd7e787e75 - 27
0x7ffd7e787e76 - 00
0x7ffd7e787e77 - 00

CodePudding user response:

unsigned char *p1 = p; there is no other use for it in the function.

But there is. void has no size and arithmetics on a void* wouldn't know how far a "step" when trying to step the pointer to the next element of the pointed out type, as p1 ; means. Where should it point after adding 1?

char, that is the smallest addressable entity, on the other hand, has a well defined size (1), and p1 means the same as stepping one char (byte) in memory, resulting in pointing at the next char (byte).


void is special. You can't instantiate/store void. void is what you use to define a procedure/function that has no return value, void func(...);. It's also what's used to define a function that doesn't accept any arguments, ... func(void);.

A void* can be used to point at any type of object, of any size, from a char, with size 1, to a megaobject, of size gigantic. void* is therefore often used to accept pointers to any type of object - but, actually stepping a pointer 1 step ahead means "step to the next object of the pointed out type in memory" which also means that the compiler needs to know the size of the object the pointer is pointing at. Converting the void* to a (unsigned) char* and using that pointer lets the function step (p1 ) forward in memory, one byte at a time.

CodePudding user response:

unsigned char *p1 = p; converts the value of p from void * to unsigned char * and stores it in p1. This conversion yields the same address but with information that it points to a different type.

printf("%p - x\n", p1, *p1); should properly be printf("%p - hhx\n", (void *) p1, *p1);. In this, %p formats the address passed to it (the value of p1) for display, so it shows a memory address in a human-readable way. Since the type of p1 is unsigned char *, *p1 is an unsigned char at the address p1 points to, and hhx converts its value to a hexadecimal numeral with at least 2 digits, using a leading 0 digit if necessary.

  • Related