0

I am creating 1d arrays B and T of n size and a 2D array A of nxn size,where n has been computed earlier. But the program crashes after Pause, what am i possibly doing wrong??

float *B = malloc(sizeof(int) * (n));
float *T = malloc(sizeof(int) * (n));
system("PAUSE");
float **A;                                                    
A = malloc(sizeof(int) * (n));
for(j = 0; j < n; j++)
{ 
    A[j] = malloc(sizeof(int) * (j));
}

i, j and n are integers.

1
  • 1
    sizeof(int) isn't good here, it should be sizeof(float) and sizeof(float*) for A. Commented Aug 29, 2012 at 7:54

2 Answers 2

3

a 2D array A of nxn size

You're passing the wrong types to sizeof. You should be using sizeof(float) and sizeof(float *). But the more serious (and insidious) problem is:

A[j]=(float*)malloc(sizeof(int)*(j));
                                 ^

You want n instead of j.

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

3 Comments

Even more serious problem: casting the return value of malloc() in C.
But how does allocating a triangular shape cause a crash?
@BoPersson The OP said "a 2D array A of nxn size". So presumably that's how it's being used.
1

Never repeat the type name in the argument to malloc(); doing so makes it easy to say the wrong type, which creates errors.

You should use sizeof, like so:

float *B = malloc(n * sizeof *B);
float **A = malloc(n * sizeof *A);
for(j = 0; j < n; ++j)
  A[j] = malloc(n * sizeof *A[j]);

Also, in C you shouldn't cast the return value of malloc().

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.