cpointersmemorymallocnull-character

How to get all characters including null characters('\0') from character pointer in C?


i have character pointer input and have set 50 bytes of memory for it. After i take input from keyboard using scanf , for example "apple" then i assume that remaining spaces are filled with null character. if it is so , how can i get all the characters or memory location including location of null characters. Is there any way to do it?

int main() {
    char *input;
    int size;

    input = (char *)malloc(50);
    printf("%s\n", "enter something:");
    scanf("%s", input);

    size = strlen(input) + 1;

Solution

  • The string manipulation functions work on strings. If you want to treat your character array as a character array instead of a string, just avoid the string functions (generally, those that are named str*). eg:

    #include <stdio.h>
    
    int
    main(int argc, char **argv)
    {
        char input[50] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw";
        printf("%s\n", "enter something:");
        if( 1 == scanf("%49s", input)) {
            fwrite(input, sizeof(char), sizeof input, stdout);
            putchar('\n');
        }
        return 0;
    }
    

    Be aware that if you are expecting to view this data, the non-printable characters will probably not be rendered well. In particular, if you view the data in a terminal, the null character written by scanf may cause some confusion. YMMV.