char [length] initialization and dealing with it

前端 未结 5 1385
长情又很酷
长情又很酷 2021-01-28 08:42

I have defined a char array:

char d[6];

Correct me if I\'m wrong regarding following:

At this moment no memory is allocated for variabl

5条回答
  •  面向向阳花
    2021-01-28 09:25

    At this moment no memory allocated for variable d.

    Incorrect. This:

    char d[6];
    

    is an uninitialised array of 6 chars and memory, on stack, has been allocated for it. Stack variables do not need to be explicitly free()d, whether they are initialised or not. The memory used by a stack variable will be released when it goes out of scope. Only pointers obtained via malloc(), realloc() or calloc() should be passed to free().

    To initialise:

    char d[6] = "aaaaa"; /* 5 'a's and one null terminator. */
    

    or:

    char d[] = "aaaaa"; /* The size of the array is inferred. */
    

    And, as already noted by mathematician1975, array assignment is illegal:

    char d[] = "aaaaa"; /* OK, initialisation. */
    d = "aaaaa";        /* !OK, assignment. */
    

    strcpy(), strncpy(), memcpy(), snprintf(), etc can be used to copy into d after declaration, or assignment of char to individual elements of d.


    How to know was char[] initialized? I need pattern if filled(d){..}

    If the arrays are null terminated you can use strcmp()

    if (0 == strcmp("aaaaaa", d))
    {
        /* Filled with 'a's. */
    }
    

    or use memcmp() if not null terminated:

    if (0 == memcmp("aaaaaa", d, 6))
    {
        /* Filled with 'a's. */
    }
    

    How to fill char[] with one kind of characters?

    Use memset():

    memset(d, 'a', sizeof(d)); /* WARNING: no null terminator. */
    

    or:

    char d[] = { 'a', 'a', 'a', 'a', 'a', 'a' }; /* Again, no null. */
    

提交回复
热议问题