Removed
Removed

Reputation: 145

Using Pointers in lieu of Arrays

I am definitely new to the C game, and would love some help with the following 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]);
    }

    return 0;
}

I understand that it segfaults because I'm giving scanf a NULL pointer, so is there any way to allow scanf to feed values into this pointer? Or is there a better method to get a variable number of arguments from stdin which I'm missing entirely?

Upvotes: 2

Views: 87

Answers (2)

ayusha
ayusha

Reputation: 484

heights pointer does not contain any memory.so first you have to allocate the memory using malloc system call according to the requirement. syntax for malloc in your case -

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

one thing to remember, after dynamic memeory location you have to free it.syntax for memory free -

free(heights)

Upvotes: 3

haccks
haccks

Reputation: 105992

Use malloc to dynamically allocate space for heights.

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

And free pointer by calling free(heights) when you are done with heights.

For small value of cases you can use variable length arrays:

 int heights[cases];

and do not forget to compile your code in C99 mode (-std=c99).

Upvotes: 7

Related Questions