简体   繁体   中英

Why does this dynamic allocation doesn't work

int a = 0;
int b = 0;

scanf("%d %d", &a, &b);

int** p = NULL;
p = (int**)malloc(sizeof(int*) * a);
for (int k = 0; k < b; k++)
{
    p[k] = (int*)malloc(sizeof(int) * b);
}

p[3][0] = 3;

When I enter 4 3 for a and b , the program doesn't run properly.
Newbie in coding

Wrong iteration count. Use a . @Nate Eldredge

Code also tidied.

p = malloc(sizeof *p * a);

// for (int k = 0; k < b; k++)
for (int k = 0; k < a; k++) {
  p[k] = malloc(sizeof p[k][0] * b);
}

Robust code would also check for allocation success (not shown).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM