Reputation: 207
int *m[10], n[10][10];
int a[] = {1,2,3,4,5,6,7,8,9,10};
m[4] = a;
Which of the following would give error upon trying to print the value and why? (Assume even n[10][10] to be initialized appropriately)
1) m[2][4]
2) n[2]
3) m[3]
(PS: Please explain in detail)
Upvotes: 0
Views: 107
Reputation: 310
The compiler won't complain when you try to create each of these things, but you likely won't get the print out values you expect.
int *m[10]
is creating an array of 10 pointers to ints. This could point to 10 different ints, or (as I suspect you are thinking) it could point to 10 "arrays" of ints. The problem here is context (it often is in C); we don't know exactly what you are trying to do. An int*
points to a memory location that holds an int
. This might be a single int
or it might be an array of ints
. Your code doesn't have any other setup information - not malloc'ing or setting a pointer equal to the address of an int - so we don't know. When you print it out we don't know what you might get, as the memory doesn't seem to be created yet (according to the code we see here).
The n[10][10] is (on most systems) going to be set automatically to a 10x10 array initialized to 0 - but we can't count on that. Regardless, we don't know what is going to print out. If you print out using printf
you could print the value of the memory address that n[2] holds. Probably not what you want. If you don't print it out as a pointer, but instead use the %d modifier of printf
, the compiler will likely show a warning but will allow it. What prints out will the an address interpreted as an integer. Probably not what you want either.
Printing out m[3] is the same issue as with n[2] concerning whether it prints an int or a pointer. However, (possibly) unlike n m's memory doesn't appear (from your code) to ever be setup. It will likely (on most systems) print out a 0 as it is probably set to a null pointer by default. Once again though, I don't know that we can count on that.
People are often taught that with C there are multiple ways to do things - and that is true. But what they aren't usually taught is there is a proper context to do most things, or a when to use one method or another. Largely the contexts are defined by whether we are using compile time or run-time allocated memory. You need to read up on memory management in C and learn more about what the Stack and Heap are for before you will really understand the differences.
Upvotes: 1