0

I'm having trouble in memorizing input of undefined length. I searched everywhere but i cannot resolve this problem. I create a personal function for realloc but it doesnt' work. gcc displays an invalid next size error. while if i use directly array=realloc(array,size) it works. this is the code:

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



void my_realloc(int *pointer, int dim){

  int *temp = realloc(pointer, dim*sizeof(int)); 
  if(temp != NULL){
     pointer = temp;
  }

}



int main(){

 int *numbers = malloc(sizeof(int)); int input,div,n=-1,size=0;

 while(scanf("%d", &input) && input != -1){

   ++size;
   my_realloc(numbers, size);

   numbers[++n] = input;

 }

 printf("insert divider\n");
 scanf("%d", &div);

 int *result = penultimate(numbers, n, div);

 if(result != NULL)
   printf("%d", *result);

 free(numbers);free(result);

 return 0;
}

also the function to find the penultimate multiple crashes due to memory leak

  int *penultimate(int *array, int length, int divider){

     int *multiples = malloc(sizeof(int)); int index=-1,size_mul=0;

     for(int i=0;i<=length;i++){
        if(array[i] % divider == 0){
           ++size_mul;
           multiples = realloc(multiples, size_mul*sizeof(int));

          multiples[++index]=array[i];
        }  
     }

     if (index-1 >= 0){
        return &multiples[index-1];

     }
      return NULL;

  }

thank you in advance guys.

ale54
  • 11
  • 1
    Search for *emulating pass by reference in c*. Then think about how your `my_realloc` function might be affected by that. – Some programmer dude Jul 02 '17 at 10:52
  • What @Someprogrammerdude says. Note that the C call 'someFunction(someType arg);' cannot possibly modify 'arg'. – ThingyWotsit Jul 02 '17 at 10:58
  • @ThingyWotsit: Well, it can not possible modify what's being passed in, being copied into in `arg`, but `arg` itself very well can be modified. – alk Jul 02 '17 at 11:12
  • @alk not by the call, it can't. The parameter can be modded, sure, but the argument can not. – ThingyWotsit Jul 02 '17 at 11:16
  • 1
    @ThingyWotsit That comment is confusing because `f(T x)` is not valid syntax for a function call. It's just `f(x)`. – melpomene Jul 02 '17 at 11:25
  • 3
    This is basically https://stackoverflow.com/questions/41526782/can-i-change-an-initialized-char-pointer-via-function. Not sure if it's an exact duplicate. – melpomene Jul 02 '17 at 11:29
  • Oh, thank you very much guys – ale54 Jul 02 '17 at 12:49
  • i can confirm that it's a duplicate of an existing question. i'm so sorry but this means that i didn't understand entirely pointers in C and it wasn't a realloc problem. thank you again – ale54 Jul 02 '17 at 16:37
  • @melpomene yes, youre right. My bad. Blame beer :) – ThingyWotsit Jul 02 '17 at 18:58

0 Answers0