dynamic memory allocation

using malloc for a 2d array

Page 1 of 1

3 Replies - 914 Views - Last Post: 10 February 2007 - 11:48 AM Rate Topic: -----

#1 keems21  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 185
  • Joined: 03-February 07

dynamic memory allocation

Posted 07 February 2007 - 02:08 PM

Well I've got this assignment for my programming class and no matter how many different ways I try and work around this problem, it never seems to work.

Here's an example of code that I'm trying to get to work:
#include <stdio.h>
int main()
{
  int **a, x, y;
  
  a = (int**)malloc(sizeof(int*) * 3 * 4);
}



Now I'm under the impression that this code should create the array a[3][4].

So I should be able to navigate the array using either of the following:
for(x = 0; x < 3; x++)
{
  for(y = 0; y < 4; y++)
  {
	a[x][y] = 5;
	//or
	*(*(a+x)+y) = 5;
  }
}



The problem with the above code is that I keep getting a segmentation error before any of the values are ever read into the array.

What am I doing wrong?

Is This A Good Question/Topic? 0
  • +

Replies To: dynamic memory allocation

#2 ByteWyse  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 41
  • Joined: 02-January 07

Re: dynamic memory allocation

Posted 07 February 2007 - 06:45 PM

You are allocating an array of pointer-to-int rather than an array of int's.
   int **a;
   a = (int **)malloc(sizeof(int *) * 3 * 4);
   // At this point, a points to an array of pointer-to-int which has
   // not yet been initialized.



Alternatively, you could simply allocate storage for int's directly:
   int *a;
   a = (int *)malloc(sizeof(int) * 3 * 4);


Was This Post Helpful? 0
  • +
  • -

#3 mattman059  Icon User is offline

  • Epic Awesomeness
  • member icon

Reputation: 15
  • View blog
  • Posts: 538
  • Joined: 23-October 06

Re: dynamic memory allocation

Posted 07 February 2007 - 07:12 PM

The way its done in C++ is:

int size, 
int* myArray;

cin >> size;

myArray = new int[size];


/* Your code goes here to fill the array */

delete [] myArray;
myArray = NULL;


Was This Post Helpful? 0
  • +
  • -

#4 keems21  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 185
  • Joined: 03-February 07

Re: dynamic memory allocation

Posted 10 February 2007 - 11:48 AM

Alright, thanks guys. I figured out what I was doing wrong. I guess I just got a little ahead of myself.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1