Difference between char s[] and char *s declarations in C

In this article we will learn the difference between two methods of string declaration, using array and pointer in C language.
Submitted by Abhishek Pathak, on November 08, 2017

The string in C can be declared in two ways. Using the array literals and other one is using the pointers. We will discuss the major differences between the two and what are different implementations during run time and compile time. Here's a code that shows the both the declaration.

Code

//Using Array literal
char str[] = "Include Help";

//Using Pointers
char *str = "Include Help";

The former declaration, that is declaration with array literal, creates one object, a char array of size 13, called str, initialised with the values 'I', 'n', 'c', 'l', 'u', 'd', 'e', ' ', 'H', 'e', 'l', 'p', '\0' .

This array is allocated in memory and it's lifetime depends on where the declaration appears. If the declaration is within a function, it will live until the end of the block that it is declared in, and almost certainly be allocated on the stack. But if it's outside a function, it will probably be stored within an "initialised data segment" that is loaded from the executable file into writeable memory when the program is run.

The latter declaration, that is declaration using the pointers, it creates two objects. A read-only array of 13 chars (similar to array literal method), which has no name and has static storage duration (meaning that it lives for the entire life of the program) and another pointer variable of type pointer-to-char, called str, which is initialised with the location of the first character in that unnamed, read-only array.

In other words, using the array literal method, it puts the literal string in read-only memory and copies the string to newly allocated memory on the stack and using the pointer method it will place "Include Help" in the read-only parts of the memory, and making s a pointer to that makes any writing operation on this memory illegal.

If you like the article, please share your comments below.


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.