Mnkisd
Mnkisd

Reputation: 512

How to free a dynamic allocated array from another function without making that array global?

#include <stdio.h>

char *mystrcat(char *s1, const char *s2);    // prototype


char *newstring;    // global pointer

int main(){
    char string1[] = "test1";
    char string2[] = "test1";

    printf("Final string: %s\n", mystrcat(string1, string2));
    free(newstring);    // I'd like to free the array here, without using a global array
}

char *mystrcat(char *s1, const char *s2){

    unsigned int len1=0;
    while (*(s1+len1)!='\0') {  // to count lenght of first string
        len1+=1;
    }

    unsigned int len2 = 0;
    while (*(s2+len2)!='\0') {  // to count lenght of second string
        len2+=1;
    }

    newstring = calloc(len1+len2+1, sizeof(char));

    unsigned int i = 0;
    size_t main_count = 0;
    for (; main_count<len1; ++main_count, ++i){
        *(newstring+main_count) = *(s1+i);
    }
    i = 0;
    for (; main_count<len1+len2; ++main_count, ++i){
        *(newstring+main_count) = *(s2+i);
    }

    return newstring;
}

This is a program to concatenate two strings. The thing is that I am doing an exercise and I must use that prototype, and I can't change it, so I can't pass the array for reference. So how can I return the array to main and then free that array (in main) without using a global array outside main?

Upvotes: 0

Views: 327

Answers (1)

Michael Bianconi
Michael Bianconi

Reputation: 5242

You are already returning newstring from mystrcat, you simply need to store it in a variable.

int main(){
    char string1[] = "test1";
    char string2[] = "test1";
    char* newstring = mystrcat(string1, string2);

    printf("Final string: %s\n", newstring);
    free(newstring);
}

Upvotes: 2

Related Questions