Allen
Allen

Reputation: 49

Problems when using realloc() in a function to resize the int pointer

I want to make a int* with size of 10 first and write a add() function to add elements. If the numbers of elements are bigger than 10, the function will use realloc() to resize the int*. However I got the error message. How can I improve this?

Here is what I did:

int main()
{
    int size = 10;
    int* a;
    a = (int*)malloc(size*sizeof(int*));
    int i;
    double start, stop;
    start = clock();

    for (i = 0; i < 100000; i++){
        add(&a, i, size, i);
    }

    stop = clock();
    printf("Adding arry by one: %10.2f\n", stop - start);

    return 0;
}


void add(int *a, int element, int size, int index)
{
    if (index < size)
    {
        a[index] = element;
    }
    else if (index >= size)
    {
        a = realloc(a, sizeof(int*)*(index + 1));
        a[index] = element;
    }
}

Upvotes: 2

Views: 215

Answers (3)

Twinkle
Twinkle

Reputation: 524

Malloc and realloc should be done for size of(int) not for size of(int*)

Upvotes: 0

You have to change the int * a parameter to int ** a. I have made some changes on the structure:

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

#define SIZE 10

void add(int**a, int element, int size, int index) {
  if (index >= size) {
    *a = realloc(*a, sizeof(int)*(index + 1));
  }
  (*a)[index] = element;
}

int main() {
  int *a = malloc(SIZE*sizeof(int));
  double start, stop;

  start = clock();

  for (int i = 0; i < 100000; i++) {
    add(&a, i, SIZE, i);
  }

  stop = clock();

  printf("Adding arry by one: %10.2f\n", stop - start);

  free(a);

  return 0;
 }

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

Your pointer a is a parameter of the function add. Parameters are just local variables in that function, so when you assign a = realloc (...) the a in the calling function isn't changed. This will crash rather quickly. size is also not adjusted - if you added an element at index 17, then index 12, your array would be resized to 13 elements.

You can use BLUEPIXY's solution. I'd prefer creating a struct containing a pointer and a size, and passing that around and letting code update it. Avoids to many **s; they are not good for your brain :-)

Upvotes: 2

Related Questions