# Thread: Integers on the heap

1. ## Integers on the heap

For a task I'm supposed to read in integers from the command line and then sum them up after putting them onto the heap.Now, I'm quite rusty with using malloc and strings and whatnot because we're pretty new to them, but I've had some experience with putting string of characters onto the heap.

This is my first time putting integers onto the heap though, and I'm very stuck.

What I have so far:

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *heap(int argc, char *argv[]);
int sum();

int main(int argc, char *argv[]) {
//int sum = 0;
int *value = NULL;

if (argc > 1) {
value = heap(argc, argv);
if (value == NULL) {
fprintf(stderr, "Memory Error\n");
return EXIT_FAILURE;
}
}

return EXIT_SUCCESS;
}

int *heap(int length, char *argv[]) {
int *value = NULL;

value = malloc(length * sizeof(int));
if (value != NULL) {
//INSERT HERE
}
return value;
}```
I'm completely clueless with what to do in the comment that says INSERT HERE. The argv values are strings of characters (even if integers are input) so I can't just put them onto the heap... Any advice?

2. Therefore, you need to access argv and convert argv[1] to argv[argc - 1] to int, writing the result to consecutive elements of the dynamic array. Also, note that the length should be argc - 1, not argc, since argv[0] is not going to be a numeric string to convert.

3. Originally Posted by laserlight
Therefore, you need to access argv and convert argv[1] to argv[argc - 1] to int, writing the result to consecutive elements of the dynamic array. Also, note that the length should be argc - 1, not argc, since argv[0] is not going to be a numeric string to convert.
Thanks for the tip I was then able to move on and get the program working by using the atoi function.
Oh and I understand that the number of integers I would have would be argc-1 but for the malloc I needed to put in length=argc to make room for the null terminator.

4. Originally Posted by Mentallic
but for the malloc I needed to put in length=argc to make room for the null terminator.
There is no need for a null terminator since you are keeping track of the number of elements of the array that is in use. Furthermore, 0 is a valid integer value.

5. Originally Posted by Mentallic
[...]make room for the null terminator.
Why would you think it necessary to have a null terminator in this case?

6. Sorry about the late reply. I can see your point of the null terminator being unnecessary, but I suppose it's good practice to use it regardless. At least, that's what we're expected in class.
We are also supposed to declare all our variables before they're used, even though we'll soon be changing the variable's value with a scanf and such, so giving the malloc a little extra room doesn't seem like such a big deal