Re: Feedback on C code?
So I have been looking at pointers off and on today, and they don't seem too terrible from a conceptual standpoint. My questions are below:
1. What happens if something like this gets executed?
int number = 5
int * pNumber = number;
Obviously, we're missing the & before number, but what happens when I try to dereference pNumber? When I tried to print the value of the pointer, the program just froze for a bit and exited without any complaints. No output was shown, which is expected, but no error messages were raised during compilation or runtime, either.
2. Do I always, always, always have to do this even if I know with 100% certainty that my pointers will never be NULL?
int number = 5;
int * pNumber = &number;
if (pNumber) {
//...
}
3. What is the use of having constant pointers? I.e
int number = 5;
const int * pNumber = number;
It seems pointless because I can still change what the pointer points to, I just can't change the actual address of the pointer, i.e
//Combined with our previous example
int number2 = 6;
pNumber = &number2;
When would I ever use this?
4. Going by the same note, why would I use the following?
int number = 5;
int * const pNumber2 = &number;
Yes, that is perfectly legal as far as I know.
5. So I now understand what y'all meant when you said when saying pointer to array relationship. Trouble is, I am now confused as to how to loop through an array
int values[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int * pValues = values; //Points to the first element in the array
//Now, I can do this:
for (int i = 0; i < 10; i ++) {
pValues ++;
printf("%d\n", *pValues);
}
That will go through the array, but it will also add in another variable, i, which I might as well use to subscript the array to access the values. So, what's the point of having a pointer?
I can't do this:
for (; pValues < 10; pValues ++) {
//...
}
From what I gathered, if I just type in the pointer name, the compiler will think that I am trying to access the address in memory the pointer points to (a hexadecimal representation which will not equal 10).
So what am I missing here?
That's as far as I've gotten today because of the headaches of the const int * pointer and int * const pointer. Oh, and you can also do const int * const pointer, too, which doesn't help me at all.
-- Audiogames-reflector mailing list Audiogames-reflector@sabahattin-gucukoglu.com https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector