简体   繁体   中英

What is the best way to initialize the string array in c?

What is the best way to initialize the string array in c?

I tried following two things

char arr[10] = "\0";
char arr1[10] = {"\0"};

After initializing those string, I tried to display in gdb, both gave the same initialization format.

(gdb) p arr
$1 = "\000\000\000\000\000\000\000\000\000"
(gdb) p arr1
$2 = "\000\000\000\000\000\000\000\000\000"
(gdb) 

I like to know which is best and what are the advantage and disadvantages.

Code:-

int main(){
    char arr[10] = "\0";
    char arr1[10] = {"\0"};

return 0;
}

Assembly:-

(gdb) disass main
Dump of assembler code for function main:

0x00000000004004ec <+0>:    push   %rbp
0x00000000004004ed <+1>:    mov    %rsp,%rbp
0x00000000004004f0 <+4>:    movzwl 0xd5(%rip),%eax        # 0x4005cc
0x00000000004004f7 <+11>:   mov    %ax,-0x10(%rbp)
0x00000000004004fb <+15>:   movq   $0x0,-0xe(%rbp)
0x0000000000400503 <+23>:   movzwl 0xc2(%rip),%eax        # 0x4005cc
0x000000000040050a <+30>:   mov    %ax,-0x20(%rbp)
0x000000000040050e <+34>:   movq   $0x0,-0x1e(%rbp)
0x0000000000400516 <+42>:   mov    $0x0,%eax
0x000000000040051b <+47>:   pop    %rbp
0x000000000040051c <+48>:   retq   

Both initializations are completely equivalent. From the standard:

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces.

Your two initializations are equivalent.

Apart from what you had shown there are several ways which a string (not only [] array) can be initialized:

// fixed size, depending on the lenght of the string, no memory "wasted"
char arr1[] = "value";

// fixed array size, depends on a given number, some memory may be unused
char arr2[10] = "value";

// C-array type initialiation
char arr3[] = {'v','a','l','u','e','\0'};

// special string, should never be modified, need not be freed
char* str1 = "value";

// a dynamic string based on a constant value; has to be freed, but can be reallocated at will
char* str2 = strdup("value");

char arr[10] = "\\0"; and char arr1[10] = {"\\0"}; are equal.

The statements

char arr[10] = "\0";

and

char arr1[10] = {"\0"};

are exactly the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM