0

How does the following program work to initialize a 2D Array, store data in it and then calculate the sum of all the elements.

I am actually bothered about how dynamic memory allocation is actually working in this code.

This approach is new to me as I couldn't find any resource that could explain this code.

#include <stdio.h>
#include <stdlib.h>

#define col 5
int main(){
    int n, i, j, sum =0;
    int (*a) [col];
    printf("Enter number of rows: ");
    scanf("%d", &n);
    a = (int (*)[col])malloc(n * col * sizeof(int));

    for(i = 0; i < n; i++){
        for (j=0; j < col ; ++j){
            //pointer to 5 elements row
            scanf("%d", &a[i][j]);
            sum+= a[i][j];
        }
    }

    printf("Sum : %d\n",sum);

    free(a);
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • **C and C++ are different programming languages.** Choose one. Your [mre] is in C. Read [this C reference](https://en.cppreference.com/w/c) and **read [*Modern C*](https://modernc.gforge.inria.fr/) if you want to learn C. Read also the documentation of your C compiler (e.g. [GCC](http://gcc.gnu.org/)...) and of your debugger (e.g. [GDB](https://www.gnu.org/software/gdb/)...)** – Basile Starynkevitch Dec 13 '20 at 08:16
  • This is not how arrays of this sort are usually defined. The `int (*a)[col]` definition is usually expressed as `int**a`, or even better, a 1D array is used, and then 2D emulation is applied. – tadman Dec 13 '20 at 08:16
  • Also, [malloc](https://en.cppreference.com/w/c/memory) can fail, and your code does not handle that failure. Of course [scanf](https://en.cppreference.com/w/c/io/fscanf) can also fail, and your code does not handle that case. If you use [GCC](http://gcc.gnu.org/) compile with all warnings and debug info, so use `gcc -Wall -Wextra -g`. With [GDB](https://www.gnu.org/software/gdb/) you can observe the dynamic behavior of your program by running it [step by step](https://sourceware.org/gdb/onlinedocs/gdb/Continuing-and-Stepping.html) – Basile Starynkevitch Dec 13 '20 at 08:20
  • What does the line ```a = (int (*)[col])malloc(n * col * sizeof(int));``` do ? Can someone explain please. – Parth Pratim Chatterjee Dec 13 '20 at 08:57
  • @PrathPratimChaterjee: **What book did you read on C programming?** The answer is inside such books, and dozen of pages are needed for an explanation. We won't write these for you alone. You might also dive inside the source code of simple C compilers, such as [nwcc](http://nwcc.sourceforge.net/), to understand how a C compiler is parsing that line. – Basile Starynkevitch Dec 13 '20 at 11:05

1 Answers1

0

I am actually bothered about how dynamic memory allocation is actually working in this code.

Read first Modern C or some other good book about C

then see this C reference. Late, read for example some C17 draft standard, e.g. n2176. It is specifying the behavior of malloc(3). Read also more about the call stack, automatic variables, and C dynamic memory allocation.

This approach is new to me as I couldn't find any resource that could explain this code.

Consider studying the source code of GNU libc. It is implementing malloc (on Linux, above syscalls(2) such as mmap(2)...)

And read also a good operating system textbook. You might understand how malloc works on ordinary OSes. It is related to virtual address space since sometimes malloc is growing that space.

Read of course the documentation of your C compiler (e.g. GCC). Enable all warnings and debug info, so use gcc -Wall -Wextra -g. Then read the documentation of your debugger (e.g. GDB) and run your program step by step under your debugger.

BTW, your code is wrong: both malloc(3) and scanf(3) could fail, and you don't check that.

At last, take inspiration from existing open source software coded in C, like GNU bash or GNU bison or GPP or GTK.


C and C++ are different programming languages

Your question mentions C++. C and C++ are very different. For C++, read first a good C++ programming book. Then see this C++ reference. Later, take inspiration from existing C++ open source software, such as fish, Qt, FLTK, RefPerSys and many others on github.


Consider using static source code analyzer tools

Such as Frama-C, the Clang static analyzer, and in 2021 perhaps Bismon.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547