'Arrays and integers in c

In this example I want to print out the number 4. This is a simplified version of my problem, but my issue is the same. After assigning b a value (in this case 4), I want to print out the 4th element of the array, not directly, but by using a separate integer (c). However a 0 gets printed out as a result. I have no idea why. Would be glad if you could help. Thanks a lot in advance!

#include <stdio.h>
#include <stdlib.h>

int numbers[10], a, b, c;

int main() {
    for (a = 0; a < 11; a++) {
        numbers[a] = a;
    }
    b = 7 - 3;
    numbers[b] = c;
    printf("%d", c);
    return 0;
}


Solution 1:[1]

Instead of setting the 4th element of the array, you should read it and store it into c:

c = numbers[b];

Also note that the initialization loop runs one step too far, assigning non-existent element numbers[10].

Here is a modified version:

#include <stdio.h>

int main() {
    int numbers[10], a, b, c;

    for (a = 0; a < 10; a++) {
        numbers[a] = a;
    }
    b = 7 - 3;
    c = numbers[b];
    printf("%d\n", c);
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chqrlie