Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an error in my function that returns values in an array using pointers in C

I am trying to learn arrays and pointers in C. I'm trying to write a program that in a function: gets 2 numbers from the user, puts them in an array, and returns them to the main function. I am getting an error and I don't understand what the problem is. Here is my code:

#include<stdio.h>

void get_nums(float *x)
{
    float num1, num2;

    printf("enter two numbers: ");
    scanf("%f %f", &num1, &num2);

    *x[0] = num1;
    *x[1] = num2;

}

main(){

    float x[2];
    float (*p_x)[2] = &x;

    get_nums(p_x[2]);

    printf("Number 1: %f\nNumber 2: %f", x[0], x[1]);

    return 0;
}

I am getting an error on these 2 lines

    *x[0] = num1;
    *x[1] = num2;

The error message is

Error: operand of '*' must be a pointer

I don't see what it is that is wrong. Does anyone see the problem?

EDIT: I changed the 2 lines to

    x[0] = num1;
    x[1] = num2;

and now I can run the program. However I get a new error after I enter the two numbers. The error message is:

  Unhandled exception at 0x40e00000 in arraysandpointers.exe: 0xC0000005: Access violation.
like image 434
Petefic Avatar asked Mar 16 '26 12:03

Petefic


2 Answers

You don't need the *. Just this is fine:

x[0] = num1;
x[1] = num2;

In your original code x[0] already is of type float. *x[0] will try to deference it - which is not possible since x[0] isn't a pointer. Therefore it doesn't compile.

EDIT : Also change your main to this:

int main(){

    float x[2];
    get_nums(x);

    printf("Number 1: %f\nNumber 2: %f", x[0], x[1]);

    return 0;
}

It is not necessary to have the p_x. And it is what's causing the crash.

like image 145
Mysticial Avatar answered Mar 19 '26 02:03

Mysticial


*X can be considered as an array of X like X[]. So when you are writing as *X[0] it considers as a 2D array. So remove the pointers in X[0] and X[1].

Remove these two lines:

float (*p_x)[2] = &x;
get_nums(p_x[2]);

You can directly do get_nums(x).

like image 28
Aizen Avatar answered Mar 19 '26 03:03

Aizen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!