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.
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
.
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()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.