Home Ask Login Register

Developers Planet

Your answer is one click away!

TyCharm February 2016

C: adding elements to an array

I'm trying to test a program that creates an array with 0 elements in it, then adds elements to it (reallocating memory each time), and then printing out the elements. But, I keep getting errors when I try to run it.

int main(int argc, const char * argv[]) {
    int num = 0;
    int n = 10;
    int **array = malloc(0);
    for (int i = 0; i < n; ++i)
        array = realloc(array, num * sizeof(int*));
        array[num-1] = &i; 

    for (int j = 0; j < n; ++j)
        printf("%d", &array[j]); // error 1
    return 0;

I'm sorry I didn't include the errors with the original post. I think I fixed one of them. Here is the other:

Error 1: Format specifies type 'int' but the argument has type 'int *'


Andrew Truckle February 2016

printf("%d", &array[j]); // error 1

The & is the address operator. So it is making something a pointer. Your array is already an array of pointers to integer.

By using the & you are trying to print the address of the integer pointer itself.

Try using * instead of &. * means that you want to print the value of the integer pointer.

printf("%d", *array[j]); // error 1

Weather Vane February 2016

This answer is based on the assumption that you are printing a simple array, since you don't show what output you expect. You are using one more step of indirection than you need, and too many variables. Take note that indexing is different from length (often by 1).

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

int main(void) {
    int i, n = 10;
    int *array = NULL;                  // no need for double star, or fake allocation
    for (i = 0; i < n; ++i)
        array = realloc(array, (i + 1) * sizeof(int));  // remove the *, add 1 for num elements
        array[i] = i;
    for (i = 0; i < n; ++i)
        printf("%d", array[i]);                 // remove the &

    free(array);                                // don't forget this
    return 0;

Program output:


In practice, you should assign the result of realloc to another pointer variable, check it's ok, and then replace the original pointer var.

Post Status

Asked in February 2016
Viewed 3,629 times
Voted 8
Answered 2 times


Leave an answer

Quote of the day: live life