Difference Between char s[] and char *s in C Programming
Difference Between char s[] and char *s in C with Examples
In C programming, char s[] and char *s are two ways to represent strings, but they have significant differences in how they allocate and manage memory. Understanding these differences is essential for effective string handling and memory management in C.
1. char s[]: Character Array
- Definition: char s[] declares a character array. The size is typically determined at the time of initialization.
- Memory Allocation: The array size is fixed once initialized, and memory is allocated on the stack (if it's a local variable).
- Modification: You can modify the contents of char s[], provided the array is not declared as const.
- Lifetime: The array exists within the scope where it’s defined.
Example: Using char s[]
In this example, s is an array that stores "Hello". Modifying s[0] to 'h' is allowed, as the array contents are stored directly in the stack memory for main().
Code:
Output:
hello
2. char *s: Character Pointer
- Definition: char *s declares a pointer to a character, typically pointing to a string literal or dynamic memory.
- Memory Allocation: Memory for char *s may be allocated on the heap (using malloc) or may refer to a string literal in read-only memory.
- Modification: If char *s points to a string literal (e.g., "Hello"), modifying it leads to undefined behavior. Only strings allocated in writable memory (e.g., with malloc) can be modified safely.
- Lifetime: The pointer itself is local, but the string literal or dynamically allocated memory may have a different lifetime.
Example: Using char *s with a String Literal
In this example, s points to a read-only string literal "Hello", so attempting to modify s[0] would lead to undefined behavior or a runtime error.
Code:
Output:
Hello
Example Comparison: char s[] vs char *s
Here’s a side-by-side comparison to clarify further:
Code:
Output:
s1: hello s2: Hello
Key Differences
Feature | char s[] | char *s |
---|---|---|
Memory Location | Stack | Heap or read-only memory |
Mutable Content | Yes | No (if pointing to string literal) |
Initialization | Requires explicit size or initialization | Can point to any string location |
Usage Context | Safer for local modifiable data | Flexible for dynamic or constant data |
Summary:
- char s[] is ideal for mutable strings with fixed size and scope-limited storage.
- char *s is versatile, used for dynamic strings or read-only literals, but is restricted in mutability when pointing to literals.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics