How to define a pointer to a 2-dimesional array of pointers.

Write here if you have problems with your C++ source code

Moderator: Board moderators

How to define a pointer to a 2-dimesional array of pointers.

Postby ImLazy » Wed Nov 05, 2008 6:15 am

This code:
Code: Select all
#include <iostream>
using namespace std;
int main() {
    int a[2][3] = { {1, 2, 3}, {4, 5, 6} };
    int *(*b)[3];
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            b[i][j] = &a[i][j];
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            cout << *b[i][j] << " ";
    cout << endl;
    return 0;
};

I get this RUNTIME ERROR:
Code: Select all
Program received signal SIGSEGV, Segmentation fault.
0x0040147c in main () at test-p.cpp:8
8                   b[i][j] = &a[i][j];

I want each element of b[][] is a pointer to an element of a[][].
I stay home. Don't call me out.
User avatar
ImLazy
Experienced poster
 
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Re: How to define a pointer to a 2-dimesional array of pointers.

Postby mf » Wed Nov 05, 2008 7:09 am

int *(*b)[3]; is a pointer to an array of 3 pointers to int.
int *(*b)[3][3]; is a pointer to a 3x3 array of pointers to int.

There's a handy utility cdecl which can do this kinds of conversions between C and plain english for you. And when in doubt you can always use typedef to simplify declarations.

As for SIGSEGV, you should've allocated memory for this 3x3 array before accessing it (or else it points to nothing), and access it like (*b)[i][j].
mf
Guru
 
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland

Re: How to define a pointer to a 2-dimesional array of pointers.

Postby ImLazy » Wed Nov 05, 2008 7:47 am

:oops: , I forget to allocate memory for b.
I stay home. Don't call me out.
User avatar
ImLazy
Experienced poster
 
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China


Return to C++

Who is online

Users browsing this forum: Bing [Bot] and 1 guest

cron