0

Below is the code I am trying to test out. I have a table size 2x4 for which I am trying to pass the address to a pointer which is going to be used by a lookup function. The code works as expected and I am receiving the correct values but I am getting the following warning:

warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]

Below is the code:

#include <stdio.h>

float lookup(float const *lookuppointer, int lookupindexX)
{
    float value;

    value = lookuppointer[lookupindexX];
    return(value);

}

int main()
{
    float cal1[2][4] = {{0,1,2,3},{4,5,6,7}};
    float value;
    float *pointer[4];

    *pointer = cal1;

    printf("The address of pointer is %p \n", pointer);

    value = lookup(*pointer,6);
    printf("The value is %f \n", value);

    printf("cal1 = %f", cal1[1][2]);



    return 0;
}

Also for some reason I need to add a size when defining the pointer, and I can put any number and it works (e.g. float *pointer[n]), I do not understand the reason behind it as well.

  • What type do you intent `pointer` to be? Is it meant to be an array of 4 `float*`, or a pointer to an array of 4 `float`? – Human-Compiler Jun 03 '20 at 17:43
  • There is no need to declare `pointer` as an array if you just want it to point into `cal1`. Just declare it as `float *`; – stark Jun 03 '20 at 17:46

1 Answers1

3

I am trying to pass the address to a pointer

float *pointer[4];

This is not a pointer. This is an array of 4 pointers to float. These pointers cannot point to an element of float cal1[2][4] because those elements are arrays of float rather than singular float objects.

An element of float cal1[2][4] is an array of 4 floats. To point to such element, you need to create a pointer to an array of 4 floats:

float (*pointer)[4];
*pointer = cal1;

This indirects through a pointer that you haven't initialised and attempts to assign the object that isn't being pointed at. The behaviour would be undefined, if the program wasn't ill-formed.

Now, if the pointer was to an array such as an element of cal1, this would not work because arrays are not assignable.

You may have intended to assign the pointer rather than the pointed object. That an be achieved by not indirecting through the pointer:

pointer = cal1;
Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326