Home > Software engineering >  How to set the in-param pointer key value correctly into the pointer in my struct?
How to set the in-param pointer key value correctly into the pointer in my struct?

Time:12-18

Alright, so I have the following in-param: uint8_t * key

In the function such as void functionname(uint8_t * key) i want to store ONLY the key itself and not the pointer to key within a new pointer called uint8_t * pointerKey (which belongs to a struct). How do I do to store only the actual key value of key and not the pointer of key into pointerKey?

is it pointerKey = &key or pointerKey = *key or pointerKey = key? haven't really gotten the grasp of this part of pointers yet, so clearing this upp would help me in the future.

CodePudding user response:

First of all, I'd suppose that your uint8_t * key input parameter contains actual data of uint8_t type, but not the pointer to other location in memory. So then, let's consider the next case:

  1. Suppose you have a struct, called KeyHolder:
struct KeyHolder {
  uint8_t *pointerKey;
}
  1. You've pointed that you want to store actual key value within a new pointer:
void functionname(uint8_t * key) {
  // get the actual value of key
  uint8_t key_value = *key;
  // allocate memory for struct
  struct KeyHolder *kh = (KeyHolder *) malloc(sizeof(KeyHolder));
  // allocate memory for storing key value
  kh->pointerKey = (uint8_t*) malloc(sizeof(uint8_t));
  *(kh->pointerKey) = key_value;

   // Do actual work ...
   // Don't forget to free allocated memory
   free(kh.pointerKey);
   free(kh);
}

Therefore, after getting the pointer of type 'uint8_t' you can store any value of specified type, in your case - key value. If you don't want to allocate memory for 'KeyHolder' struct you should write it like that:

struct KeyHolder kh;
kh.pointerKey = (uint8_t *) malloc(sizeof(uint8_t));
*(kh.pointerKey) = key;

CodePudding user response:

It depends if the argument for functionname(uint8_t *key) is address of an integer, or pointer for integer array. If it's an integer:

void foo_integer(uint8_t* ptr)
{
    printf("foo, ptr = %d\n", *ptr); //read the value
    *ptr = 123; //changes the variable which ptr points to
}

You can use this function by pass the address of integer variable:

int key = 0;
foo_integer(&key);
printf("key changed: %d\n", key); //key is changed to 123

If the argument is an array, you just pass the pointer, for example

void foo_integer_array(uint8_t* ptr, int count)
{
    if (count < 0) return;
    ptr[0] = 1000; //okay
    for (int i = 0; i < count; i  ) 
        printf("arr %d, ", ptr[i]);
    printf("\n");

    //*ptr = ? <- don't dereference ptr, we are not allowed to change it
}

int arr[3] = { 1,2,3 };
foo_integer_array(arr, sizeof(arr)/sizeof(*arr));

You just pass arr to foo_integer_array (the array arr will decay to pointer, it is already an address), you wouldn't pass the address of the arr.

  •  Tags:  
  • c
  • Related