Home > Blockchain >  Pointer to pointer in c source file
Pointer to pointer in c source file

Time:09-17

I see a code which says the following.

typedef struct dummy
{
    int a;
    int b[100];
} dummy_t;

typedef struct dummya
{
    int a;
    int b;
} dummya_t;


void * getptr(){
    // return a pointer of a memory
}

void function(){
    dummya_t*dstptr = getptr();
    dummy_t *srcpt = (dummy_t*)(dstptr->b);
}

I can see dummy_t *srcpt = (dummy_t*)(dstptr->b); meaning as a pointer is pointing to another pointer but then *srcpt should be a double pointer right? Like **srcpt

CodePudding user response:

Your code is not correct, you can not cast nor assign using pointers to objects of different types, for example:

struct a { int a, b; };
struct b { int a, b; };

are different objects even having the same members.

struct a x = {.a = 1, .b = 2};
struct b *y = &x; // wrong

I can see dummy_t srcpt = (dummy_t)(dstptr->b); meaning as a pointer is pointing to another pointer but then *srcpt should be a double pointer right? Like **srcpt

Your assumptions are not correct, a basic example using plain pointers to int:

#include <stdio.h>

int main(void)
{
    int arr[] = {1, 2};
    int *a = &arr[0];
    int *b = &arr[1];

    printf("a = %d b = %d\n", *a, *b);

    int **ptr;

    ptr = &a;
    *ptr = &arr[1];
    ptr = &b;
    *ptr = &arr[0];

    printf("a = %d b = %d\n", *a, *b);

    return 0;
}

The output is:

a = 1 b = 2
a = 2 b = 1

As you can see, you use a double pointer (**ptr) when you want to change the contents of a or b (the address where it points to), a more useful example:

#include <stdio.h>

void swap(int **a, int **b)
{
    int *temp = *a;

    *a = *b;
    *b = temp;
}

int main(void)
{
    int arr[] = {1, 2};
    int *a = &arr[0];
    int *b = &arr[1];

    printf("a = %d b = %d\n", *a, *b);

    swap(&a, &b);

    printf("a = %d b = %d\n", *a, *b);

    return 0;
}

Same output:

a = 1 b = 2
a = 2 b = 1

CodePudding user response:

I can see dummy_t *srcpt = (dummy_t*)(dstptr->b); meaning as a pointer is pointing to another pointer but then *srcpt should be a double pointer right? Like **srcpt

No. That line means "treat the value of dstptr->b as though it were a value of type dummy_t *, and assign it to srcpt". It's not a pointer to a pointer.

The expression dstptr->b has type int, which cannot be directly assigned to a pointer type. (dummy_t *) is a cast, which tells the compiler to convert the type.

Like Vlad says in his comment, this code doesn't make any sense. It may compile, but just because it compiles doesn't mean it's right.

  • Related