0

I have two arrays of pointers. I need to do simple arithmetic with them while going in loop

 float **x_points, **y_points;

x_points = malloc(sizeof(float*) * n);
y_points = malloc(sizeof(float*) * n);

for( i = 0; i < n; i++) {
    printf("x");
    printf("%i",i);
    printf(" : ");
    x_points[i] = malloc( n * sizeof ( float ) );
    scanf("%f",x_points[i]);

    printf("y");
    printf("%i",i);
    printf(" : ");
    y_points[i] = malloc( n * sizeof ( float ) );
    scanf("%f",y_points[i]);
}

x_points[n] = NULL;
y_points[n] = NULL;

And here I have problems:

int k;

for(k=0; k < i; k++) {
    R += *x_points[k] * *y_points[k+1] - *x_points[k+1] * *y_points[k];
}

Couldn't you tell me why does this code shows me a window says that the system got a signal and that's why stopped the program? THank you, I will appreciate it!

1
  • This code has multiple problems, not just with that loop (the placement of which remains a mystery because you haven't posted an SSCCE). Commented Mar 5, 2014 at 12:03

3 Answers 3

1

You're allocating n pointers:

x_points = malloc(sizeof(float*) * n);
y_points = malloc(sizeof(float*) * n);

but here you're accessing past of the memory you've allocated:

x_points[n] = NULL;
y_points[n] = NULL;

Since C is 0-based for indices, you can only go from 0 to n-1.

So you either need to allocate n+1, or to put your null at n-1

Edit: also what hmjd said. I didn't catch it.

Sign up to request clarification or add additional context in comments.

Comments

0

The reason could be that you are accessing un-allocated memory location.
Change

for(k=0; k < i; k++)  

to

for(k=0; k < i - 1; k++)

Comments

0
x_points[n] = NULL;
y_points[n] = NULL; 

is also invalid as your assigning the value outside the memory allocated to it.

change the malloc call a bit if wanna still achieve this

malloc( n+1 * sizeof ( float ) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.