0

I have created the pointer, and allocated memory to it. This memory should contain the number, that I'm passing inside in array style (1 number = 1 element), also, the 0 element is the size of the number. However, I'm facing the problem of changing data inside the allocated memory, using a pointer. If I'm using my code in the main function, everything goes perfect, but when I created another function and passed a pointer value inside, I can't save it back (if the number is bigger then 99999 and takes 6 elements to be stored).

The main function:

int *convNum=NULL;

int main() {
int num;
convNum = malloc(sizeof(int));
if (convNum==NULL){
    printf("Allocation error\n");
    exit(0);
}

scanf("%d", &num);
convNum[0] = numLength(num);
printf("%d\n", convNum[0]);
convertNum(num, convNum);

for (int i = 1; i<=convNum[0]; i++){
    printf("%d", convNum[i]);
}

printf("\n");

return 0;
}

The function, that I'm trying to use

int convertNum(int num, int * convNum){
int temp = num;
int size = convNum[0];
convNum = realloc(convNum, sizeof(int)*(size+1));
if (convNum==NULL){
    printf("Allocation error\n");
    exit(0);
}
for (int i=size;i>0;i--){
    convNum[i] = temp % 10;
    temp = temp / 10;
}
return 0;
}

EDITED The output with the number size less, than 6 gives me the result I needed. The output with other numbers gives me broken size (something like -10349945820) and no proper result.

Matthew Darens
  • 129
  • 2
  • 8
  • 1
    Possible duplicate of [C - pointers as function arguments](https://stackoverflow.com/questions/18698317/c-pointers-as-function-arguments) – Michael Albers Jul 09 '17 at 03:55
  • Possible duplicate of [C Programming: malloc() inside another function](https://stackoverflow.com/questions/2838038/c-programming-malloc-inside-another-function) – melpomene Jul 09 '17 at 04:18

1 Answers1

0

Your reallocation is not surviving your function call to convertNum. See this topic in the C-Faq:

Pointer to pointer clarification

You should pass the convNum pointer by-reference.

Mark Benningfield
  • 2,800
  • 9
  • 31
  • 31
  • Thanks, I have changed to "int convertNum(int num, int **convNumber)" and "convertNum(num, &convNum)". Then I have tried "convNumber[i] = temp % 10;" inside the function, as I found at pointer to pointer info. However, it saves everything to "convNumber", not to "convNum". And if I'm trying "*convNumber[i] = temp % 10;" it leads to segmentation fault. Please advice. Thank you. – Matthew Darens Jul 09 '17 at 04:51
  • @MatthewDarens OK, hang on. Don't try and post another question in a comment. Take the time to assimilate the new information. Maybe read up some more on pointers. Then, post another question. We will try to help you. We will NOT write your code for you. – Mark Benningfield Jul 09 '17 at 05:11