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

Time:12-04

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;

CodePudding user response:

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("Is", 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.

CodePudding user response:

or example "apple" then i assume that remaining spaces are filled with null character

Your assumption is wrong. All other elements in the array have undermined values.

how can i get all the characters or memory location including location of null characters. Is there any way to do it?

You cant access the characters beyond the null character using any string functions. But you can access them as "normal" elements of the array

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

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

    for(size_t i = 0; i < 50; i  )
    {
        printf("Char no [%zu] is 0xx = %s\n", i, input[i], (input[i] >= ' ' && input[i] < 127) ? (char[]){'\'', input[i], '\'', 0} : "not printable");
    }
}
  • Related