Solved

2D array dynamic memory allocation

Posted on 2003-11-09
8
9,979 Views
Last Modified: 2010-05-18

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
Comment
Question by:sanko50
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 3

Expert Comment

by:komar
ID: 9710838
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
 
LVL 3

Expert Comment

by:freewell
ID: 9712012
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
 
LVL 5

Expert Comment

by:g0rath
ID: 9714965
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.

 

Author Comment

by:sanko50
ID: 9720981

(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
 
LVL 3

Accepted Solution

by:
komar earned 30 total points
ID: 9721241
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
 

Author Comment

by:sanko50
ID: 9724590


"..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
 
LVL 5

Expert Comment

by:g0rath
ID: 9724667
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
 
LVL 3

Expert Comment

by:komar
ID: 9724883
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
Suggested Courses

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question