My question revolves around pointers passed as a multidimensional array. I’m doing something wrong here and hopefully someone can provide some guidance.
I want to pass a multidimensional array of string to a function as a parameter. Within the function I want to iterate through the elements, printing each one out to the console.
Read that small book again: K & R. There is no replacement for that. Students should read it several times and each time you read it you will learn something new.
Thanks, that helps clarify it a bit. So basically when you pass in states to the displayStates function, you’re passing in the address of states? Because when I run
printf("%p",states);
I get a memory address. That would make sense if states merely contains the memory address of the array of strings? From what I understand, pointers never contain values, they contain memory addresses that may in turn contain values.
For some reason, I have a lot of trouble understanding pointers.
The name of an array is the same as the address of its first element, i.e. states == &states[0]. So there is no “address of states” since it’s not a scalar, it’s really the address of its first element.
Pointers and arrays are some of the hardest things to understand in C, but once you have grasped it, you can congratulate yourself. Read many expositions on the topic, in books or in online tutes and eventually you will get the picture.
Yes, you are beginning to get the picture. But be careful when writing functions. If you intend to use the pointer again further down the function, you have changed the copy of it passed in. In that case you should iterate using a copy of the pointer.
In this case I’m using a copy of pstates. Also while it’s a matter of taste, and makes absolutely no difference to the code generated, I prefer to make my pointer comparison explicit.
*p != 0 as opposed to *p in the test of the for.
PS: Note to bystanders, 0 there is not really integer zero, (a null pointer does not have to actually have the address 0, although I know of no implementation that doesn’t use address 0), read K&R for the special meaning of the bare token 0 with regard to pointers. This was somewhat obscured in later C standards which allowed any expression with a value of 0, such as 0x0, etc.