Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char Array VS Char *

Tags:

c++

This is a question based on answers from question:

const char myVar* vs. const char myVar[]

const char* x = "Hello World!";
const char  x[] = "Hello World!";

I understand the difference now, but my new questions are:

(1) What happens to the "Hello World" string in the first line if I reassign x? Nothing will be pointing to it by that point - would it be destroyed when the scope ended?

(2) Aside from the const-ness, how are the values in the two examples differently stored in memory by the compiler?

like image 526
John Humphreys Avatar asked Aug 16 '11 18:08

John Humphreys


People also ask

What is the difference between char * and char array?

The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "Test" , while the pointer simply refers to the contents of the string (which in this case is immutable). Why is char* str commonly used when str denotes a string.

Is a char array the same as a char pointer?

For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string. So this is read-only.

What is a char * array in C?

In C, an array of type char is used to represent a character string, the end of which is marked by a byte set to 0 (also known as a NUL character)

What is the difference between char a [] string and char * p string?

char a[]="string"; // a is an array of characters. char *p="string"; // p is a string literal having static allocation. Any attempt to modify contents of p leads to Undefined Behavior since string literals are stored in read-only section of memory.


1 Answers

Placing "Hello World!" in your code causes the compiler to include that string in the compiled executable. When the program is executed that string is created in memory before the call to main and, I believe, even before the assembly call to __start (which is when static initializers begin running). The contents of char * x are not allocated using new or malloc, or in the stack frame of main, and therefore cannot be unallocated.

However, a char x[20] = "Hello World" declared within a function or method is allocated on the stack, and while in scope, there will actually be two copies of that "Hello World" in memory - one pre-loaded with the executable, one in the stack-allocated buffer.

like image 198
wberry Avatar answered Nov 08 '22 16:11

wberry