[C] I made it as a practice, but I don't know why output comes out like this even if I keep thinking about it. It's going to be easy, but please take a look.

Asked 2 years ago, Updated 2 years ago, 43 views

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

char *Mystrrev(char *string) {
    char *NewStr = NULL;
    int count = 0;

    for (int i = 0; string[i] != '\0'; i++) count++;

    NewStr = (char*)calloc(count, sizeof(char));

    for(int j = 0; count > 0; j++){
        NewStr[j] = string[count];
        count--;
    }

    free(NewStr);
    return NewStr;
}

int main(void) {
    char *str[3] = { "Hello", "World", "String" };
    char* *ppstr = str;

    puts(Mystrrev(ppstr[1]));

}

Hello! I made it while studying books by myself! It's really not an assignment

It doesn't show any errors or outputs. (Normal operation!) I can)

I've seen the code made by someone else in this question, but I think I need to point out why it doesn't work

I'm asking because I'm struggling alone and I can't move on.

(The problem is to create a MyStrrev() function that can perform the same function as the strrev() function! )

Thank you!

c pointer

2022-09-20 20:08

2 Answers

Please refer to the code below.

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

char* Mystrrev(char* string) {
    char* NewStr = NULL;
    int count = 0;

    for (int i = 0; string[i] != '\0'; i++)
        count++;

    NewStr = (char*)calloc(count + 1, sizeof(char));

    if (NewStr != NULL)
    {
        for (int j = 0; j < count; j++)
        {
            NewStr[j] = string[count - 1 - j];
        }

        NewStr[count] = '\0';
    }

    return NewStr;
}

int main(void) {
    char* p = NULL;
    char* str[3] = { "Hello", "World", "String" };
    char** ppstr = str;

    puts(ppstr[1]);

    p = Mystrrev(ppstr[1]);
    puts(p);

    free(p);
    p = NULL;
}


2022-09-20 20:08

Release the space of NewStr in the function and return it. I think you need to think about the location of free (NewStr).


2022-09-20 20:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.