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
Selected Reading
How to create a pointer for strings using C language?
In C programming, you can create pointers to strings using arrays of pointers. An array of pointers to strings is an array where each element is a pointer that holds the base address of a string literal or character array.
Syntax
char *array_name[size] = {"string1", "string2", "string3", ...};
Here, each element array_name[i] is a pointer to the base address of the corresponding string.
Advantages
- No fixed memory size requirement − strings occupy only the necessary bytes
- No memory wastage compared to 2D character arrays
- Efficient storage for strings of varying lengths
Example 1: Basic Array of String Pointers
#include <stdio.h>
int main() {
char *a[5] = {"one", "two", "three", "four", "five"};
int i;
printf("The strings are: ");
for (i = 0; i < 5; i++) {
printf("%s ", a[i]);
}
printf("<br>");
return 0;
}
The strings are: one two three four five
Example 2: Student Names Array
#include <stdio.h>
int main() {
char *students[] = {"bhanu", "ramu", "hari", "pinky"};
int i;
printf("The names of students are:<br>");
for (i = 0; i < 4; i++) {
printf("%s<br>", students[i]);
}
return 0;
}
The names of students are: bhanu ramu hari pinky
Key Points
- Each pointer in the array points to a string literal stored in read-only memory
- The array size can be omitted during initialization − compiler determines it automatically
- More memory-efficient than 2D character arrays for variable-length strings
Conclusion
Arrays of string pointers provide an efficient way to handle multiple strings in C. They save memory by avoiding fixed-size allocation and allow easy access to strings through pointer dereferencing.
Advertisements
