Error in data output C


I have a problem, I am learning C and I am "translating / converting" my Java code to C to make it more efficient, just that I have a problem in the output: It is assumed that the output must be 11 15 18, but only the 15 leaves correctly and the others do not. The program makes the sum of data in the same position. In advance thanks for the help. JAVA code

public static void main(String[] args) {
    Scanner leer = new Scanner(;
    int n;
    n = leer.nextInt();
    int a[] = new int[n];

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a.length; j++) {
            a[j] += leer.nextInt();
    for (int i = 0; i < a.length; i++) {
        System.out.print(a[i] + " ");

Code C

int main(){
int n,aux=0;
int a[n];
for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
        //printf("%i ",aux);
for(int i=0;i<n;i++){
    printf("%i  ",a[i]);
return 0;

Exit in C

 10165323  15  10163090 



1 2 3
3 4 5
7 8 9

Expected output

11 15 18
asked by Crxwler 08.11.2017 в 02:10

2 answers

int a[n];

There you are reserving space to store n elements of type int ... but the memory locations are not manually initialized, so if you do not initialize them by hand they will have random values (garbage).

You are missing this:

for(int i=0; i<n; i++)
  a[i] = 0;

Or this:


The fact that only the second case is correct is random (depends on how the memory leaves the previous instructions)

answered by 09.11.2017 / 13:19

You have realized that you have to initialize them to zero but it has its why.

In c declare a variable is reserving a memory space, this space could have been used previously by another program and has left data that we will call garbage for your current program.

By reserving the memory and not removing the garbage, what you are getting is the data that you had previously.

Global variables on the other hand if initialized to 0 if you do not give them a value.

answered by 09.11.2017 в 13:07