pointersarehard
pointersarehard

Reputation: 71

Multiply two float elements in an array that is referenced using pointers

How do I multiply two values that are inside an array that is referenced using a pointer? Example:

void func(float *a[3]) {
    //a[0]*a[1] // generates compiler errors
    float x = (*a[0])*(*a[1]) // this does not generate any errors when compiled but results in Segmentation fault 11. However it works when printing out to console: printf("%f", (*a[0])); => 1
}

int main() {
    float arr[3] = {1, 2, 3};
    float *ptr = arr;

    func(&ptr);
    
    return 1;
}

Upvotes: 1

Views: 240

Answers (2)

deeper-understanding
deeper-understanding

Reputation: 81

You program should be more like this:

#include <stdio.h>

void func(float *a) {
  float x = a[0] * a[1];
  printf("%f", x);
}

int main() {
  float arr[3] = {2, 4, 6};
  float *ptr = arr;

  func(ptr);
    
  return 1;
}

arr and ptr have the same value really, which is an address of the beginning of float numbers in RAM (you can think of it as RAM but in reality it is virtual memory). You pass that pointer into func, and then a is a pointer to the very first float number. You can use those values either by a[1] or *(a + 1). So you can write a[0] * a[1] or *a * *(a + 1). You can also directly use func(arr) instead of func(ptr) because arr and ptr have the same value.

Upvotes: 3

Ian Abbott
Ian Abbott

Reputation: 17403

float *a[3] is an array of three pointers to float, not a pointer to an array length 3 of float. Since this is a function parameter, the declaration of the parameter of array of float * is adjusted to be a pointer to a float *. Therefore, the parameter declaration float *a[3] is equivalent to float **a.

Your code passes &ptr to the function. ptr is of type float *, so &ptr is of type float **. So &ptr is compatible with the function parameter. However, ptr is not an array of float *. It is a single float *. The rules of C allow &ptr to treated as a pointer to the first element of an array of length 1 of float *. Inside the function func, a[0] is valid, but a[1] is out of bounds.

To pass an array to a function, the usual technique is to pass a pointer to the first element of the array. The simplest solution to your problem is to change the function parameter to float *a (or float a[]), as in the following:

#include <stdio.h>

void func(float *a) {
    float x = a[0] * a[1];
    printf("%f", x);
}

int main() {
    float arr[3] = {1, 2, 3};

    func(arr);
    return 0;
}

Upvotes: 1

Related Questions