Question

I have a weird bug with the length of my strings. I'm fairly new at this so it's probably something basic I am missing out.

I'm trying to write a program that gets a pointer to an array of characters (IE first character of the string) and it returns a pointer to a string of the same size as the first one, but the letters are reversed. For example Computer will become retupmoC. tacocat will stay tacocat :)

here's the code:

char* return_flipped_string(char* stringptr)
{
    int i=0,size_of_string=length_of_string(stringptr);
    char *flipped;
    flipped=(char *)malloc(size_of_string*sizeof(char));
    while(i<size_of_string)
    {
        *(flipped+i)=*(stringptr+size_of_string-1-i);
        i++;
    }
    return flipped;
}

stringptr is a pointer to the original string, flipped is the one i am returning. when I print the flipped string, it shows the original one flipped, followed by indistinguishable gibberish. They are not the same size for some reason.

here's the code I wrote for finding the length of a string (working properly)

int length_of_string(char* stringptr)
{
    int length=0,i=0;
    while(*(stringptr+i)!='\0')
    {
        length++;
        i++;
    }
    return length;
}
Was it helpful?

Solution 3

You are missing a NUL terminating character. You need to allocate one additional character for flipped and add a '\0' at the end explicitly.

char* return_flipped_string(char* stringptr)
{
    int i=0,size_of_string=length_of_string(stringptr);
    char *flipped;
    flipped=(char *)malloc((size_of_string + 1)*sizeof(char));
    while(i<size_of_string)
    {
        *(flipped+i)=*(stringptr+size_of_string-1-i);
        i++;
    }
    *(flipped+1) = '\0';
    return flipped;
}

BTW - you are aware of the strlen function in the Standard Library right? Your length_of_string function duplicates it. I can't remember if strrev is in the ANSI/ISO Standard or not.

OTHER TIPS

You need to append a null byte ('\0') to the end of the flipped string. The length of the flipped string data buffer is the length of the input string plus one for the null string terminator byte. It's that null byte that tells where the string ends.

you need to NULL terminate the string.... like so..

  while(i<size_of_string)
    {
        *(flipped+i)=*(stringptr+size_of_string-1-i);
        i++;
    }
    flipped[size_of_string]=0;
    return flipped;

There is no such thing as a string in C. C has character (char) arrays, which are interpretted (by convention) as strings when they contain a NUL character ('\0'). The first NUL found terminates the string. If your array does not include a NUL, then any of the standard string functions will keep on reading the buffer beginning at the address that you provided until they encounter a null byte.

Hence the gibberish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top