Thursday, 15 May 2014

c - Using Pointers in lieu of Arrays -



c - Using Pointers in lieu of Arrays -

i new c game, , love help next code snippet:

#include <stdio.h> int main() { int cases; scanf("%d", &cases); printf("%d", cases); int i; int *heights; for(i=0; i<cases; i++){ scanf("%d", &heights[i]); } homecoming 0; }

i understand segfaults because i'm giving scanf null pointer, there way allow scanf feed values pointer? or there improve method variable number of arguments stdin i'm missing entirely?

use malloc dynamically allocate space heights.

int *heights = malloc(cases*sizeof(int));

and free pointer calling free(heights) when done heights.

for little value of cases can utilize variable length arrays:

int heights[cases];

and not forget compile code in c99 mode (-std=c99).

c pointers memory

No comments:

Post a Comment