Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

converting a multidimensional array into pointer logic

Status
Not open for further replies.

nappaji

Programmer
Mar 21, 2001
76
US
I have a piece of code that has many variables declared like

abc[1024][1024][10];

Now, i want to increase the size of all these variables to

abc[2048][2048][10];

but, whien i compile and run the program, I am getting a segmentation fault. I believe this is beacuse, it is running out of memory.

I want to make it so that it allocates memory dynamically.

How do I go about doing it?? and how do i allocate memory?? use a realloc??
 
> abc[2048][2048][10];
Well do the math - this array (if its an array of char) is 40 MBytes. If its an array of ints, that could easily be 160MBytes.
Do you even have that kind of memory?

If you have
Code:
void func ( ) {
    char abc[2048][2048][10];
}
Try making it static (preserves the scope, but moves it off the stack). Whilst most unix-like operating systems can grow the stack on demand, asking it to grow by 40MB in one hit might be a bit much.
Code:
void func ( ) {
    static char abc[2048][2048][10];
}

> I want to make it so that it allocates memory dynamically.
How you do this depends on what can vary.
If all your dimensions are fixed at compile time, then you can create the above array using malloc quite simply
Code:
void func ( ) {
    char (*abc)[2048][10] = malloc ( 2048 * sizeof *abc );
}

However, life gets a bit more interesting if you really want to allocate
Code:
void func ( ) {
    char abc[x][y][z]; // some run-time values here
}
State what you're trying to achieve here...

--
 
Thanks Salem for the quick reply.

I am in charge of maintaining a piece of software and have the task of increasing the size of these data structures.

My array is

int abc[2048][1024][10];
I want to replace these hardocded values with dynamic allocation.

Initially, during the early stage of execution, I'll know what's the exact value of the first suffix (position of 2048), then at a later stage, I read a file, based on which I'll have to allocate memory for the second and third suffixes.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top