char [length] initialization and dealing with it

断了今生、忘了曾经 提交于 2019-12-02 08:11:45
hmjd

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. */

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.

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"; 
int d[6];

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

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!