-
About arrays
Hello! I'm currently doing work with arrays, and am having trouble visualizing what is happening with my code. From what I understand,
Code:
char names[100][20];
y=0;
printf("Enter inventory type:"); scanf("%s", &z);
names[y][y]=z;
printf("[%d][%d]=%s", y, y, names[y][y]);
0
when fruit is is scanned in, looks like this...0 Fruits
But when I try to print out fruits again from the array, I encounter a problem and the program is forced to close. Can someone please explain to me where I am going wrong?
thanks,
Alex
-
z is already a pointer. you don't need to use & on it.
strings can't be copied by assignment. you have to use a loop or strcpy.
Code:
strcpy(names[y], z);
printf("[%d]=%s\n", y, names[y]);
-
I don't know what z is, so who knows what's going on there.
names[y][y] is a single character and cannot hold an entire string. names[y] is a string, so it could hold an entire string. But names[y] is not assignable with = -- you have to use strcpy, or scanf directly into it.
-
Ok, I tried what you guys said but to no avail, did I misinterpret?
Code:
int y=0;
char names[100][20], *z;
printf("Enter inventory type:"); scanf("%s", z);
strcpy(names[y], z);
printf("[%d]=%s", y, names[y]);
-
z is just a pointer to some random place in memory. that's wrong because you can't write to memory that isn't yours and memory isn't yours unless you ask for it explicitly. you have to point that pointer somewhere or make it an array. an array is better because you don't have to manage memory.
Code:
char names[100][20], z[20];
-
z has no memory assigned to it (well, z itself has 4 bytes, but when you pass z as a parameter to scanf, it is the CONTENT of those 4 bytes which is passed, that that is not deifned)
Use
instead.
Or just don't use z at all, but pass in names[y] to scanf.
--
Mats
-
Yay it ran!
Thanks a bunch =P