0

I am trying to write a simple program that stores an array and then returns it. However, it is not returning all of the numbers correctly, specifically toward the end of the array. Here is an example of the output:

Please enter number of numbers
5
Please enter number 1
2
Please enter number 2
3
Please enter number 3
5
Please enter number 4
6
Please enter number 5
7
Number 1 is 2
Number 2 is 3
Number 3 is 5
Number 4 is 14
Number 5 is 1
logout

[Process completed]

and here is my code:

#include <stdio.h>

int main (void) {
    int i, num;
    int x[num];

    printf("Please enter number of numbers\n");
    scanf("%d",&num);

    for (i = 0; i < num; i++) {
        printf("Please enter number %d\n", i + 1);
        scanf("%d",&x[i]);
    }
    for (i = 0; i < num; i++) {
        printf("Number %d is %d\n", i + 1, x[i]);
    }

    return 0;
}
1
  • regarding the calls to the scanf() function: the returned value (not the converted parameter value) needs to be checked to assure the input/conversion operation was successful Commented Apr 6, 2015 at 20:29

2 Answers 2

2

Before scanning num you are doing int x[num] and as num stores garbage value you aren't getting the correct output.

int main (void) {
    int i, num;
   // int x[num]; // num is not defined here

    printf("Please enter number of numbers\n");
    scanf("%d",&num);
     int x[num];

    for (i = 0; i < num; i++) {
        printf("Please enter number %d\n", i + 1);
        scanf("%d",&x[i]);
    }
    for (i = 0; i < num; i++) {
        printf("Number %d is %d\n", i + 1, x[i]);
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Note: This is only valid C99 and later. Using malloc to allocate the array is far more portable. Which of the two is the "best practice" depends on industry / application.
@BrianMcFarland Yeah... How is this implemented in C99..? Is the malloc indirectly called when we declare x[num] ?
In theory it could just be a stack pointer manipulation just like a fixed-size array. Hidden calls to malloc and free would also probably work. But most of my low level debugging experience is w/ C89 (or close to it), so I couldn't really tell you.
2

I think You should initialise the num variable so that it will not be having the garbage values initially..

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.