Search code examples
cpointersreturn-valueansi-c

Unable to return char pointer from function


Using ansi c
#define STDC_VERSION 201112L

I'm new to c, but took my lead from Here

Regardless of the approaches I've tried, I can't get the sum pointer to return.

Running the code succeeds (creates the correct number), and the printf in the addNumericStrings function works, but the printf in the main does not (prints nothing). I assume due to an error prior. I'm not getting any warnings on the build.

output

addNumericStrings.sum = 11234567889

main

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

int main(void) {
    char s1[] = "9999999999";
    char s2[] = "1234567890";

    char *sum = addNumericStrings(s1, s2);
    printf("main.sum = %s\n", sum);
}

functions

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

char addNumericStrings(char *s1, char *s2);
char leftPad(char *result, char *s, int maxlength);
int  findMaxLength(char *s1, char *s2);

char addNumericStrings(char *s1, char *s2){
    int maxlength = findMaxLength(s1, s2);
    char addend1[maxlength];
    char addend2[maxlength];

    char *sum = (char *) malloc(sizeof(char) * (maxlength + 2) );

    int a1, a2, total;
    int carry = 0;

//  char sum[(maxlength + 2)]; // +1 in case addition rolls over past maxlength
    // Prepare the strings for manual addition
    leftPad(addend1, s1, maxlength);
    leftPad(addend2, s2, maxlength);
    // Buffer sum with ascii zeros (#48), not 0, and not "\0"
    for (int i = 0; i < (maxlength + 1); i++) { sum[i] = 48; }
    sum[maxlength + 1] = 0;
    // Run the manual addition
    // Start adding individual ints from end (right side)
    for (int i = maxlength - 1 ; i >= 0; i--) {
        a1 = addend1[i] - '0'; // Convert to int
        a2 = addend2[i] - '0'; // Convert to int
        total = (a1 + a2 + carry);
        carry = 0;
        if ( total >= 10){
            carry += 1;
            total -= 10;
        }
        sum[i +1] = 48+total; // convert to ascii value for numbers (adding 48)
    }
    sum[0] = 48+carry; // add last carry to start of num always, even if 0
    sum[maxlength + 1] = '\0';
    printf("addNumericStrings.sum = %s\n", sum);
    return sum;
}

char leftPad(char *result, char *s, int maxlength){
    // Pads number to [000123456789]    
    ( ...snip... )
}

int findMaxLength(char *s1, char *s2){
// Returns int value of the length of the longer between s1 and s2
    int length1 = strlen(s1);
    int length2 = strlen(s2);
    int maxlength;
    (length1 > length2) ? (maxlength = length1) : (maxlength = length2);
    return maxlength;
}

Solution

  • If you want to return a char * from your function, you have to use the appropriate return type:

    char* foo(void)
    //  ^
    {
        char *bar;
    
        // ...
    
        return bar;
    }