• 0

C++ question


Question

3 answers to this question

Recommended Posts

  • 0

//the solution above doens't work. TY for trying anyways.

I found out. It's very odd but makes sense. Here is the source of a simple program that I found on from ee.surrey.ak.uk

/* Demonstrates passing a pointer to a multidimensional */

/* array to a function. */

#include

void printarray_1(int (*ptr)[4]); //f(x) prototypes

void printarray_2(int (*ptr)[4], int n);

main()

{

int multi[3][4] = { { 1, 2, 3, 4 },

{ 5, 6, 7, 8 },

{ 9, 10, 11, 12 } };

// ptr is a pointer to an array of 4 ints. (ignore 3)

int (*ptr)[4], count;

// Set ptr to point to the first element of multi.

ptr = multi;

/* With each loop, ptr is incremented to point at the next */

/* element (that is, next 4-element integer array) of multi. */

for (count = 0; count < 3; count++)

printarray_1(ptr++);

puts("nnPress a key...");

getch();

printarray_2(multi, 3);

}

void printarray_1(int (*ptr)[4])

{

/* Prints the elements of a single four-element integer array. */

/* p is a pointer to type int. You must use a type cast */

/* to make p equal to the address in ptr. */

int *p, count;

p = (int *)ptr;

for (count = 0; count < 4; count++)

printf("n%d", *p++);

}

void printarray_2(int (*ptr)[4], int n)

{

/* Prints the elements of an n by four-element integer array. */

int *p, count;

p = (int *)ptr;

for (count = 0; count < (4 * n); count++)

printf("n%d", *p++);

}

Link to comment
https://www.neowin.net/forum/topic/5387-c-question/#findComment-37668
Share on other sites

  • 0

Well although you already seem to have the solution ... heres what i've done ... it works rly well for me.

this is just initializing it .. (and this is off the top of my head there may be errors but the thing is they should be easy to understand and fix.

char ***ptr; //Multi-Dimensional Pointer

ptr = new char **[3];

for (int i = 0; i < 3; i++) {

ptr = new char *[3];

}

for (i = 0; i < 3; i++) {

for (int x = 0;x < 3; x++) {

ptr[x] = new char [3];

}

}

//ptr can now be accessed as follows:

//ptr[1][1][1] <-- Just like a real array.

I however am a complete newbie to pointers. I just thought about this and thought. .. is this defeating the whole purpose of pointers or is it valid ... can anyone answer my question please? thanks =)

Link to comment
https://www.neowin.net/forum/topic/5387-c-question/#findComment-37673
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.