chrisgjh chrisgjh - 4 months ago 12
C Question

Getting weird output when practising using pointer in c

Here is my programme:

#include <stdio.h>

int tokenCopy(char* dest, const char* src, int destSize)
{
int i;
for (i = 0; i < destSize-1; i++) {
if (src[i] != '\0' && src[i] != EOF && src[i] != ' '){
dest[i] = src[i];
} else {
dest[i] = '\0';
break;
}
}
return i;
}

int main()
{
char buff[5];
int n = tokenCopy(buff, "This is a string", 5);
printf("%d '%s'\n", n, buff);
}


I tried to use this to copy extract a string from a string to another string. With this test case, I supposed to get
4 'This'
. But I get
4 'This´┐Ż'
instead. I know somehow my loop terminates an index later than it supposed to be, but I do not know how to fix it.

I know there is built in function could help me with this situation, but I really want to find out the problem, thanks

Answer

The for loop will run until it's complete (the else case inside the loop will never happen), and then you just return from the function without adding the terminator to the destination string.

You need to add the terminator after the loop, not in the else inside the loop.


The fixed function should look like

int tokenCopy(char* dest, const char* src, int destSize)
{
    int i;
    for (i = 0; i < destSize-1; i++) {
        if (src[i] != '\0' && src[i] != ' '){
            dest[i] = src[i];
        } else {
            // Don't terminate here, just break out of the loop
            break;
        }
    }
    dest[i] = '\0';  // Terminate string
    return i;
}

Note that I also removed the EOF check, it's pretty much useless as no standard input function should put it in the array it writes to. There's also the problem that comparing the int value -1 (which is what EOF expands to) to the char value -1 will not work as you expect. If you check most input functions that returns characters, you will see that they return int.