Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between char s[] and char *s in C
In C programming, there are two common ways to declare strings: char s[] and char *s. While both can hold strings, they have fundamental differences in memory allocation, mutability, and behavior.
Syntax
char s[] = "string literal"; // Array declaration char *s = "string literal"; // Pointer declaration
Key Differences
| Aspect | char s[] | char *s |
|---|---|---|
| Type | Array of characters | Pointer to char |
| Memory Location | Stack (local array) | Pointer on stack, string in read-only section |
| Mutability | Modifiable | Read-only (undefined behavior if modified) |
| sizeof() Result | Total array size in bytes | Size of pointer (typically 4 or 8 bytes) |
Example 1: Memory Size Difference
This example demonstrates the difference in memory allocation −
#include <stdio.h>
int main() {
char s1[] = "Hello World";
char *s2 = "Hello World";
printf("sizeof(s1): %lu bytes<br>", sizeof(s1));
printf("sizeof(s2): %lu bytes<br>", sizeof(s2));
return 0;
}
sizeof(s1): 12 bytes sizeof(s2): 8 bytes
Example 2: Modifying Array String (char s[])
Arrays created with char s[] are modifiable −
#include <stdio.h>
int main() {
char s[] = "Hello World";
printf("Original: %s<br>", s);
s[6] = 'x'; // Modify character at position 6
printf("Modified: %s<br>", s);
return 0;
}
Original: Hello World Modified: Hello xorld
Example 3: Attempting to Modify Pointer String (char *s)
Trying to modify a string literal through a pointer results in undefined behavior −
#include <stdio.h>
int main() {
char *s = "Hello World";
printf("Original: %s<br>", s);
s[6] = 'x'; // Undefined behavior - may cause segmentation fault
printf("Modified: %s<br>", s);
return 0;
}
Note: The above code will likely cause a segmentation fault or runtime error because string literals are stored in read-only memory.
Key Points
-
char s[]creates a local array copy that can be modified safely. -
char *spoints to a string literal in read-only memory. - Use
char s[]when you need to modify the string content. - Use
char *sfor read-only string references to save memory.
Conclusion
Understanding the difference between char s[] and char *s is crucial for proper memory management and avoiding runtime errors. Choose arrays for modifiable strings and pointers for read-only string literals.
