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;
}
5
  • C and C++ are different programming languages. Choose one. Your minimal reproducible example is in C. Read this C reference and read Modern C if you want to learn C. Read also the documentation of your C compiler (e.g. GCC...) and of your debugger (e.g. GDB...) Commented Dec 13, 2020 at 8: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. Commented Dec 13, 2020 at 8:16
  • Also, malloc can fail, and your code does not handle that failure. Of course scanf can also fail, and your code does not handle that case. If you use GCC compile with all warnings and debug info, so use gcc -Wall -Wextra -g. With GDB you can observe the dynamic behavior of your program by running it step by step Commented Dec 13, 2020 at 8:20
  • What does the line a = (int (*)[col])malloc(n * col * sizeof(int)); do ? Can someone explain please. Commented Dec 13, 2020 at 8: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, to understand how a C compiler is parsing that line. Commented Dec 13, 2020 at 11:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Since OP is new, jumping straight to the standard & libc sources looks like a huge overkill, it's almost impossible to learn the basics of the language this way.
Yes, so I recommend to read first Modern C. Be aware that I am not a native English speaker, so feel free to improve the phrasing
What does the line a = (int (*)[col])malloc(n * col * sizeof(int)); do ? Can someone explain please.
Yes. Spend several days in reading a good C programming book. You'll understand that line once you did read and understood it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.