I’m a bit confused about pointer arrays and I just wanna make sure I’m right.
When I write int *arrit is just a pointer to an int variable, not an array yet. It is only that I initialize it (say with malloc) that it becomes an array. Am I right so far?
Also I have another question: were given (in school) a little function that is supposed to return an array of grades, with the first cell being the average. The function was deliberately wrong: what they did was to set
int *grades = getAllGrades();
And than they have decreased the pointer by one for the average ‘cell’
*(grades - 1) = getAverage();
return *(grades - 1)
I know this is wrong because the returned value is not an array, I just don’t know how to explain it. When I set a pointer, how does the machine/compiler know if I want just a pointer or an array?
(If I’m not clear its because I’m trying to ask about something that is still vague for me, my apologizes)
It doesn’t, and it never will. Suppose you
You just allsocated 12 bytes (assuming int is 4). But malloc only sees 12. Is that 1 big object or lots of little ones? It doesn’t know. The only one who actually knows is you 😉
Now about your particular example,
At this point, as you said, there’s nothing to say whether
gradespoints to an array. But you know it points to an array, and that’s what’s important. Or, maybe you know it doesn’t point to an array. The key is you have to know whatgetAllGradesdoes, to know if it’s returning an array or a pointer to 1 thing.This is not necessarily wrong, but it does look kind of sketch. If it is an array, you would expect
grades[0]==*(grade + 0)to be the first element, sogrades[-1]==*(grades - 1)looks like it would be before the first element. Again, it’s not necessarily wrong; maybe ingetAllGradesthey did:ie they scooched the start up by 1. It’s been known to happen (look in Numerical Recipes in C) but it’s kind of odd.