Solved

2D array dynamic memory allocation

Posted on 2003-11-09
8
9,934 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
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 3

Expert Comment

by:komar
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:sanko50
Comment Utility

(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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 3

Accepted Solution

by:
komar earned 30 total points
Comment Utility
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
Comment Utility


"..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
Comment Utility
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
Comment Utility
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
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.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now