Search code examples
cstringpointerscharrecv

How to terminate a string that already has a text in C?


How can I terminate a string pointer that already has a value? This is what I tried:

char* pointer = "Hello";
pointer = "\0"

This doesn't work. I am looking for a way to make something with the same concept of this work, since I am not the one declaring the value of the pointer (a function is).

The function is the recv function in <sys/socket.h> and it doesn't null terminate it for me.


Solution

  • You should know the length of your string in order to null terminate it. In your case, the recv function returns the length upon successful execution. It returns -1 otherwise.

    The variable, say str, that stores your string should be capable of storing at least length + 1 characters in it.

    Then you can do:

    ssize_t length = /* Call to recv function */;
    if (length != -1)
        str[length] = '\0';