2

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?

2
  • On a side note you are (probably) not giving anything a NULL pointer. Leaving variables unassigned means they have an undefined value so could be anything. Commented Jun 19, 2014 at 8:24
  • The main problem is heights is defined as a pointer and you have not (probably via malloc()) given it anything to point to. Commented Jun 20, 2014 at 5:34

2 Answers 2

7

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).

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

1 Comment

+1 And make a habit of invoking free() for anything you malloc().
3

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)

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.