Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 9990
  • Last Modified:

2D array dynamic memory allocation


i want to implement a 2D array using dynamic memory allocation.... i was trying to write the code like below.but it is not compiling.......where is the mistake i have commited ??

main()

 { int **a,i,j,m,n,rows,cols;



         scanf("%d%d",&rows,&cols);

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

           int** a[i]=(int*) malloc(rows*sizeof(int));

           printf("done");

         }



         for(j=0;j<cols;j++)

           {

               int* a[j] = malloc(cols*sizeof(int));
               printf("done");

           }


      for(m=0;m<rows;m++)
              for(n=0;n<cols;n++)
                      printf("%d",a[rows][cols]);


 }

......i just want to know how to implement 2D array using dynamic memory allocation....
in linux at compile time i am gettiing a message  " variable sized object may not be initialized"...what does it mean??
0
sanko50
Asked:
sanko50
  • 3
  • 2
  • 2
  • +1
1 Solution
 
komarCommented:
You seem to have some extra *'s in you code plus some extra logical errors. For example, you declared "a" to "int **" at the begining of your code an then declared it again inside the first "for" loop. Also, you are trying to pring the array contents without initializing them!

The following code does allocate 2D integer array and initializes each cell to the summation of it's indexes so that ( a[i][j] = i + j )

      #include <stdio.h>
      #include <malloc.h>

      main()
      {
            int **a = NULL;
            int rows,cols;
            int i,j;

            scanf("%d%d",&rows,&cols);

            //Allocate space for the 2D integer array pointer
            a = (int **)malloc(rows * sizeof(int *));

            //Allocate space for each row in the array (1 row == cols * sizeof(int))
            for(i = 0; i < rows; i++)
            {
                  a[i] = (int *)malloc(cols * sizeof(int));
            }
            
            //Initialize the array (for example, a[i][j] = i * j)
            for(i = 0; i < rows; i++)
                  for(j = 0; j < cols; j++)
                        a[i][j] = i + j;

            //Print array
            for(i = 0; i < rows; i++)
            {
                  for(j = 0; j < cols; j++)
                  {
                        printf("%d\t",a[i][j]);
                  }
                  printf("\r\n");
            }

            return 0;
      }

Check the comments before each block of code to know what does that block do!

Thanks,
- Khalid Omar
0
 
freewellCommented:
Just want to point out that the allocated memory needs to free before the program exists.

for(i = 0; i < rows; i++)
{
    free(a[i]);
}

free(a)
0
 
g0rathCommented:
yes please do this...I've had to clean up a K&R style C guy who never did this "...because the OS does all of this for me, why should I?"

It's proper form, and makes it easier if you ever go to a persistant model, like we did, as in CGI -&gt; Apache Module conversion.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
sanko50Author Commented:

(1) the code given by komar works whether i use "free"  or not. i know it is always suggested to use "free" while usuing malloc. but if donot use "free" then what kind of problem i wolud face????(as it will not give any compilation error!!!!!).

(2)  is it always necessary to initialize a pointer????? for example here ...int **a = NULL;

i am not getting the comments by the experts in my yahoo mail account in time nowadays. i opened my mail account and found there is no comments...then i came to experts-exchange home page and found 2 comments are already there? why not getting the comments in my mail account??


0
 
komarCommented:
Hi,

1) A programmer should always use free() to de-allocate memory previously allocated using malloc() (Actually I forgot to use it in my comment). The program I wrote is so simple and does not use that much memory so it is most likely that you wont run into memory issues. Another fact is that the program allocates memory and uses it from some purpose and exist immediately which means the OS will take care of freeing allocated memory for you.

In complex programs that dynamically allocate memory the problem might be huge if free() is not used, specially when the program is supposed to run for a long time.

2) Syntax wise, NO. You still can compile your code without initializing the pointers you declare. But as a good programming experience it is better to initialize all pointers (and variables) to 0 or NULL.

Thanks,
Khalid.
0
 
sanko50Author Commented:


"..In complex programs that dynamically allocate memory the problem might be huge if free() is not used.."

could u plz tell what exactly that problem is if  " free " is not usued?

0
 
g0rathCommented:
If you always alloc memory and never clear it, when you could, you program suffers from bloat....it gets large and large and can lead to issues down that path.

I have worked where there was never a use of free, since the application was a CGI written in C, when the client finished that request the program died and all memory went away. When it was ported to being a persistant module, there was huge bloat and crashes because of out of memory errors. It was quite hard to go and find each and every place memory was allocated and then free it when it wasn't useful anymore...memory leaks when y ou have 1000 hits to a program in an hour can stack up quickly.

Good programming practice is to take care of the what-ifs, so that later you don't lose time and money trying to track down a tiny bug related to memory.
0
 
komarCommented:
GENERAL RULE: Memory that gets allocated with malloc() is considered in use and cannot be utilized or allocated by other programs or the same program again until free() is used to free that memory block.

Memory in general is a limited resource. Windows, for example, tries to extend the physical memory "RAM" by utilizing the available hard disk space as 'virtual meory' and swapping (between HDD and RAM) when necessary, the swapping operation is a very slow operation compared to accessing the physical RAM. So, when speed is an issue, an application that uses huge memory resources (or leaks memory because of not using free()) will certainly suffer from speed/effeciency issues.

Another point is when working on application that are meant to run all the time, such as server applications. If the operation involves allocating 10KB of memory for each client that accesses the server *and not freeing this memory when the client disconnects then the server will end up owning 1MB of memory (that it does not use because the clients have already disconnected) after 100 client connections. After 100,000 client connection, the server will be using 1GB of the system memory. Few ore days of operation, the available memory will be allocated by that server application and no more applications will be able to run on that machine. Even the server itself will not be able to serve more clients and it has to be shut down.

If your program allocates a block of memory only once (e.g., at the application start-up) and utilizes that memopry block without allocating more memory depending on dynamic events, then the OS will take care of freeing that memory block when the application exists. But it is aloways a good practice to free allocated memory when the memory is no longer needed.

Thanks,
Khalid.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now