Hi, I modified your program slightly, inputs[i] is no longer assigned a value within the loop for obvious reasons (you'll see in a second).
Code:
#include <stdio.h>
int main() {
int gates;
int i;
int inputs[] = {0};
printf("Size of integer = %d\n", sizeof(int));
printf("how many gates: ");
scanf("%d", &gates);
for(i = 0; i < gates; i++) {
printf("how many inputs for gate %d:\n", i);
printf("Addr: inputs[i]\t=\t %lu\n", (unsigned long)&inputs[i]);
printf("Addr: gates\t=\t %lu\n", (unsigned long)&gates);
printf("Addr: i\t\t=\t %lu\n", (unsigned long)&i);
printf("Addr: inputs\t=\t %lu\n\n", (unsigned long)&inputs);
//scanf("%d",&inputs[i]);
}
}
Output:
saec@saeculum:~$ ./test
how many gates: 4
how many inputs for gate 0:
Addr: inputs[i] = 3214882696
Addr: gates = 3214882704
Addr: i = 3214882700
Addr: inputs = 3214882696
how many inputs for gate 1:
Addr: inputs[i] = 3214882700
Addr: gates = 3214882704
Addr: i = 3214882700
Addr: inputs = 3214882696
how many inputs for gate 2:
Addr: inputs[i] = 3214882704
Addr: gates = 3214882704
Addr: i = 3214882700
Addr: inputs = 3214882696
how many inputs for gate 3:
Addr: inputs[i] = 3214882708
Addr: gates = 3214882704
Addr: i = 3214882700
Addr: inputs = 3214882696
If you inspect the addresses of the variables, and the address that &input[i] points to you'll notice that it often coincides with the address of another variable.
When your program runs, the variables in main are placed onto a stack on after the other so the stack may look a little like this:
Code:
+--------+
| inputs | Lowest Addr
+--------+
| i |
+--------+
| gates | Highest Addr
+--------+
Remembering that the stack is upside down in the fact that the variable with the highest address on the stack is gates
This is relevant to your problem in that, at the moment your array has 4 bytes of space defined, it's essentially a pointer to the memory at which those 4 bytes begin.
When you do an operation such as:
What's actually taking place is pointer arithmetic. So essentially, the address pointed to would be: &inputs + (sizeof(int) * i ) - the size of an int on a system is generally 4 bytes.. sizeof(int) returns the number of bytes that an int is defined as being.
Your error is assuming that the inputs array is large enough to hold data being read into it by scanf.
Inspect the output and you'll notice that the address &inputs[i] is incremented by 4 each time i increases. It would then overwrite the 4 bytes of memory starting it &inputs[i]( on the stack below it in the higher memory addresses), and would eventually cause a segmentation fault in the best scenario.