-1

I try to create function that sum 2 string numbers, for example "888" and "9879" return "10767".

The problem is that when I access the return value from main I get garbage.

typedef char* verylong;
verylong add_verylong(verylong vl1, verylong vl2);
int main(){
    verylong result = add_verylong("888", "9879");
    printf("%s\n", result);
    return 0;
}
verylong add_verylong(verylong vl1, verylong vl2){
    int len_1 = strlen(vl1);
    int len_2 = strlen(vl2);
    int vl1_number= 0;
    int vl2_number = 0;
    int mul = 1;
    while(len_1 > 0){
        int x = vl1[len_1-1] - '0';
        x = x * mul;
        vl1_number = vl1_number + x;
        mul *= 10;
        len_1--;
    }
    mul = 1;
        while(len_2 > 0){
        int x = vl2[len_2-1] - '0';
        x = x * mul;
        vl2_number += x;
        mul = mul * 10;
        len_2--;
    }
    int number = vl1_number + vl2_number;
    int length = 0;
    int temp = number; 
    while(temp > 0){
        length += 1;
        temp /= 10;
    }
    length++;
    char string[length+1];
    verylong result = string;
    result[length--] = '\0';   
    while(number > 0){
        int x = number % 10;
        char c = x +'0';
        result[length] = c;
        length--;
        number /= 10;
    }
    return result;   
}

What could be the cause of this problem?

gal leshem
  • 551
  • 1
  • 6
  • 18
  • Returning pointer to local var. There are a lot of dupes. – Martin James Jan 15 '20 at 21:58
  • this is tagged C++ but the concept still applies to C: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope . Also, tell your teacher it's bad practice to hide pointers in `typedef`s, this is the 2nd "`typedef char* verylong;`" I've seen this week. – yano Jan 15 '20 at 22:00
  • https://stackoverflow.com/questions/59721462/converting-string-to-int-and-returning-string-again-c – yano Jan 15 '20 at 22:04

1 Answers1

0

Everything declared in a function that's not static will be removed from memory once the function returns. So, result address after the function execution will hold garbage not the actual output you want.

Mohammed Deifallah
  • 1,290
  • 1
  • 10
  • 25