 nextdarius - 2 years ago 114
C Question

# Malloc double pointer

My function prototype should look like this:

``````void double_min_max(int **range, int min, int max)
``````

I have to fill 'range' with number from min to max.

I don't know how to malloc the double pointer and how to assign every element the number min.

``````void    double_min_max(int **range, int min, int max)
{
range = (int **)malloc(sizeof(int)* 10);
int i = 0;
while (min < max)
{
**range[i] = min;
i++;
min++;
}
}
`````` Felix Palmen

Ok, let's spot the errors:

``````void double_min_max(int **range, int min, int max)
{
range = (int **)malloc(sizeof(int)* 10);
``````

The cast with malloc is unnecessary and could even lead to problems. Don't do this.

Then you want to assign to `*range`, not to `range`. `range` is local to your function (all arguments are passed by value in C), so modifying it will never have any effect visible to the calling code. When you call this function, you should pass a pointer to a pointer, so the pointer can be modified by the function through `*range`.

Finally, this should be obvious, but you should calculate the required size from your `min` and `max`. The `10` is just a ... uhm ... very rough guess. Not a good idea.

``````    int i = 0;
while (min < max)
{
**range[i] = min;
``````

This is wrong. `[]` does dereference the pointer, so you have three levels of dereferencing here. But it's only a pointer to pointer, not pointer to pointer to pointer. Also, indexing precedes the normal dereference, not what you want. Use `(*range)[i]` instead.

``````        i++;
min++;
}
}
``````

A sensible implementation could look like this:

``````size_t double_min_max(int **range, int min, int max)
{
// check for valid input
if (min > max) return 0;

// calculate required size
size_t size = max - min + 1;

*range = malloc(size * sizeof **range);

// check allocation succeeded:
if (!*range) return 0;

for (size_t i = 0; i < size; ++i)
{
(*range)[i] = min++;
}
return size;
}
``````

Call it like this:

``````int *range;
size_t result = double_min_max(&range, 10, 20);

// result should now be 11, the size of the array `range` points to

// when done:
free(range);
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download