如何从另一个函数中释放动态分配的数组而不使该数组成为全局数组?

问题描述 投票:0回答:1
#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;
}

这是一个连接两个字符串的程序。问题是我正在做一个练习,必须使用该原型,并且无法更改它,所以我cant将该数组作为参考。那么如何在不使用main外部的全局数组的情况下将数组返回给main并then释放该数组(在main中)?

#include char * mystrcat(char * s1,const char * s2); //原型char * newstring; //全局指针int main(){char string1 [] =“ test1”; char string2 [] =“ test1”; ...

c arrays pointers malloc global-variables
1个回答
2
投票

您已经从newstring返回mystrcat,您只需要将其存储在变量中。

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

    printf("Final string: %s\n", newstring);
    free(newstring);
}
© www.soinside.com 2019 - 2024. All rights reserved.