tags:

views:

289

answers:

3

Hi, i asked some time ago on an account i cant remember how to manipulate basic pointers and someone gave me a really good demo

for example

char *ptr = "hello" (hello = a char array)

so now *ptr is pointing at h

ptr++ = moves the ptr to point at the next element, to get its value i do *ptr and that gives me e

ok so far i hope :D but now i need to manipulate a char **ptr and was wondering how I do this in a way that mimmicks the effects of a 2d array?

some basic tips would be much appreciated as I need to do an assignment that has a **ptr to imitate a 2d array and without knowing how it does this first means I cant even solve it on paper (for example, how do you dereference a **ptr, how do you get [x][y] values etc)

thanks

+4  A: 

A pointer to a pointer is just that. For example:

// Declare our double-indirection pointer.
char** ptr;
// And initialize it:
char s1[] = "hello";
char s2[] = "world";
ptr = malloc(sizeof(char*) * 2);
ptr[0] = s1;
ptr[1] = s2;
// ptr now points to a pointer that points to 'h'.
char* ptr2 = *ptr;
// ptr2 points to 'h'.
char* ptr3 = *(ptr + 1);
// ptr3 points to "w".
char c = **ptr; // could be written as *(*ptr)
// c = 'h'.
char c2 = *(*(ptr + 1));
// c2 = 'w'.
char c3 = *(*(ptr) + 1);
// c3 = 'e'.
Max Shawabkeh
gcc throws up wome warnings on that first line (initialization from incompatible pointer type, excess elements in scalar initializer). You're using an array initializer on a non-array type.
John Bode
You are right. Edited in a fix.
Max Shawabkeh
A: 

You may use them as you would a normal two-dimensional array. (Since effectively, that's what they are)

char** ptr = {"lorem", "ipsum", "dolor"};
char* s1 = ptr[0]; //Points to the beginning of "lorem"
char* s2 = ptr[1]; //Points to the beginning of "ipsum"
char c = ptr[2][4]; //Contains 'r'

This is due to the fact that:

int *a;
//...
int i = a[6];
int j = *(a + 6); //Same as previous line!

Cheers,

Amit Ron--

Amit Ron
+6  A: 
John Bode
+1, however "`ptr` and `ptr[0]` both point to the beginning of the first string in the list" is incorrect. Unlike the case with 2D arrays (which are contiguous across all their dimensions), `ptr` does not point to the same place as `ptr[0]`.
Max Shawabkeh
To make your first example work: `char* ary[] = {"foo", "bar", "bletch"}; char** ptr = ` This would declare `ptr` as a "pointer-to-array" and since each array element is a string (which is itself an array), `ptr` is in essence a "pointer-to-array-of-arrays". Be careful when doing a double-dereference with this type of `char**` pointer; since the strings aren't the same length, you'll want to make certain you perform all necessary bounds checking.
bta
@Max - you are correct (had arrays on the brain for some reason). I've removed that statement. Thanks for the catch.
John Bode
How does double indirection gets saved in the memory?
fahad