If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

C pointers and arrays?

OK, as I understand it - and I may be wrong here - in the C programming language, pointers and arrays are "unified" meaning the following code snippet should compile:

Code:

char *msg;
msg = "Goodbye, Cruel World!";
char c;
c = msg[5];

But if I want to have a 2 dimensional array represented as a pointer, what do I do?

Like I want to have an array of character pointers, but I don't know how long the array will be and size is kind of an issue. (With using a character pointer instead of an array, the size of the character pointer is always 4 on my 32 bit machine; I found this out using the sizeof() operator.)

Is it possible to use a pointer to a pointer of a char and use it as a two dimensional array?

"The Texan turned out to be good-natured, generous and likeable. In three days no one could stand him." Catch 22 by Joseph Heller.

Yes, it is most definitely possible, and that's exactly what command line arguments are passed to your program as. If you write a C program that takes command line arguments, your main function will look like this:

Code:

int main(int argc, char * argv[]){

or it could be

Code:

int main(int argc, char ** argv){

Which both accomplish the same thing. So if you wanted an array of pointers to character pointers you could have:

Code:

char * lines[5] = { "one", "two", "three", "four", NULL };

I could have put "five" where I have NULL, but I put NULL for a reason. That's how you know when there are no more lines left.

Since NULL marks the end, you can traverse the array until you find NULL as above. With our main example above the variable argc is the number of elements in the argv array. Typically you're going to know how many elements are in the array and you can use that to traverse in a for loop, but if you don't, the last element should be NULL and you can use that knowledge to traverse until the end. I hope this helped.