C: Why do elements of an array need to be scanf'd by memory address? -
(c beginner alert)
i want read in integers user , store them in array. so:
int main (void) { int i, num, cont = 0; int arre[10]; (int i=0;i<5;i++) { scanf("%d", arre[i]); etc.
when run this, segmentation fault 11 on osx. if run valgrind, problem occurs when enter first integer, , tells me:
==1610== command: ./arraysandpointers ==1610== 2 ==1610== use of uninitialised value of size 8 ==1610== @ 0x18f0ba: __svfscanf_l (in /usr/lib/system/libsystem_c.dylib) ==1610== 0x18718a: scanf (in /usr/lib/system/libsystem_c.dylib) ==1610== 0x100000f2d: main (arraysandpointers.c:11) ==1610== ==1610== invalid write of size 4 ==1610== @ 0x18f0ba: __svfscanf_l (in /usr/lib/system/libsystem_c.dylib) ==1610== 0x18718a: scanf (in /usr/lib/system/libsystem_c.dylib) ==1610== 0x100000f2d: main (arraysandpointers.c:11) ==1610== address 0x0 not stack'd, malloc'd or (recently) free'd
if add & in front of arre[i], if fixes problem. don't know why. i'm struggling fact reading in integer, storing (apparently) memory address in array. yet when check value appears in resultant array, it's int itself, , not memory address. why so?
note: fundamentally struggling grasp pointers/memory addresses , relation arrays, char* etc. (see my other questions) , despite haven undertaken several c training modules different providers , watched various explanations online, i've yet encounter can definitively nail concept me. particularly, i'm interested know when , why pointers needed. if can suggest reference/video/tutorial/article me, grateful.
let's replace i
0 here sake of explanation.
scanf("%d", arre[0]);
this code goes array, looks first element, , finds it's 17 (or whatever), passes 17 second argument scanf()
. scanf()
expecting pointer, gets horribly confused when sees 17 , ends crashing application.
scanf("%d", &arre[0]);
this code calculates location of first element in array , passes pointer scanf()
. scanf()
happily writes value memory addressed pointer.
Comments
Post a Comment