This is a question about copying heatless after dynamic allocation of C language memory!

Asked 2 years ago, Updated 2 years ago, 31 views

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

int str_copy(char *str2, char *str1);
int str_len(char *str1);
int str_func(char **str2, char *str1);

int main(){
    char str1[50]="I Love Chewing C hahaha";
    char *str2;
    char *str3;

    str_func(&str2,str1);
    str_func(&str3,"hello");

    printf("%s\n",str1);
    printf("%s\n",*str2);
    printf("%s\n",*str3);

    free(str2);
    free(str3);

    return 0;
}

int str_func(char **str2, char *str1){
    str2=(char **)malloc(str_len(str1)*sizeof(char *)+1);
    str_copy(*str2,str1);

    return 0;
}

int str_len(char *str1){

    int count=0;
    while(*str1){
        str1++;
        count++;
    }
    return count;
}

int str_copy(char *str2, char *str1){
    while(*str1){
        *str2=*str1;
        str2++;
        str1++;
    }
    *str2='\0';

    return 0;
}

The above code is to copy the str1 string to str2 and to copy the string hello to str3. I made str2, str3 because I wanted to print out three strings of str1, str2, and str3 after dynamically allocating memory as long as the string I want to copy str2 and str3 directly, but it didn't work I want to solve the problem using a function that calculates the length of the string (str_len), a function that copies the string (str_copy), and a function that allocates the two tasks and memory (str_func), but I don't see any errors, but it doesn't work."T" I'd like to get some feedback on the problems of the above code or better ways! I'm using this site for the first time today, and I think there are a lot of talented people, so please!

c

2022-09-22 16:47

1 Answers

int str_func(char **str2, char *str1){
    str2=(char **)malloc(str_len(str1)*sizeof(char *)+1);
    str_copy(*str2,str1);

    return 0;
}

->

int str_func(char **str2, char *str1){
    *str2=(char *)malloc(str_len(str1)*sizeof(char)+1);
    str_copy(*str2,str1);

    return 0;
}
printf("%s\n",str1);
printf("%s\n",*str2);
printf("%s\n",*str3);

->

printf("%s\n",str1);
printf("%s\n",str2);
printf("%s\n",str3);


2022-09-22 16:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.