char [length] initialization and dealing with it

前端 未结 5 1377
长情又很酷
长情又很酷 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:14
    int d[6];
    

    6 bytes will be allocated onto the stack with this declaration. It will be freed automatically.

    0 讨论(0)
  • 2021-01-28 09:18

    First, whenever you declare char d[6] 6 bytes of memory is already allocated.

    Second, no need to free your memory unless you do malloc

    Third, if you want to initialize it with one kind of character then do this

    char d[6] = "aaaaa"; 
    
    0 讨论(0)
  • 2021-01-28 09:21
    How to know was char[] initialized? I need pattern if filled(d){..}
    

    Just do this while declaring the character array:

    char d[6];
    d[0] = 0;
    

    Then you can check like this:

    if(strlen(d) == 0)
    //d is not initialized
    
    0 讨论(0)
  • 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. */
    
    0 讨论(0)
  • 2021-01-28 09:30

    Your code will not compile (gcc 4.6.3) if you do

     char d[6];
     d = "aaaaa";
    

    you will need to do

     char d[6] = "aaaaa" 
    

    to initialise it this way. This is a local variable created on the stack and so in terms of memory issues all you need worry about is not writing/reading beyond the array bounds.

    0 讨论(0)
提交回复
热议问题