0

I have this piece of code (it's a samplesort algorithm with MPI in C ) which I am trying to understand but since don't know much about C I got stuck, I searched each part individually but got a bit confused. My understanding was that malloc shows where in the heap(=memory?) to save and we multiply our given numbers by the user with the sizeofint which is 4 bytes so now we have a correct allocation of memory and we cast it I guess? Though at the above line of code NoofElements are also initialized as an int (does not atoi makes the string that is argv1 which equals to first-line input by the user? ) So why do we need to cast it again?:

NoofElements = atoi(argv[1]);

Input = (int*)malloc(NoofElements * sizeof(int));

Both Input and NoofElemnts are used after in the code, but it shows a warning that they are uninitialized. Also, some other which I don't really get.

The link to the full code

My Warnings: enter image description here

Azrail
  • 47
  • 7
  • So this is Visual Studio? – jwdonahue Feb 07 '21 at 20:26
  • In VS, you can right-click on the warnings and copy them to the clip-board. Then [edit] your post to include the pasted text. I usually paste it to notepad or my code editor and clean it up a bit first. Read [ask] and please don't post images of text. Post an [mcve]. – jwdonahue Feb 07 '21 at 22:05

1 Answers1

1

In VS, if your file has the default .cpp file extension, the code is treated as if it is C++. If it's a .c extension, then the file can be interpreted as C code, with the caveat that they stopped trying to keep up with C standards, in favor of C++ development, long ago. But I did just confirm, that if it's a C file, the VS 2019 environment won't require the cast as would be required in C++.

In C, casting the return value of malloc is not required. It's also a bad idea.


Getting to your question:

NoofElements = atoi(argv[1]); // argv[1] can be NULL.

Just because the program expects an argument on the command line, doesn't mean the user will always provide one.

jwdonahue
  • 6,199
  • 2
  • 21
  • 43