Master C Arrays, Pointers, and Strings: From Basics to Advanced Tricks
This comprehensive guide explains C arrays, their ordered and indexable nature, how to define, initialize, and access both one‑dimensional and multidimensional arrays, explores pointer arrays and array pointers, demonstrates passing arrays to functions, returning array pointers, and covers essential string handling functions such as strcpy, strlen, strcmp, and strncmp.
Previous Articles
C Language Quick Start (0) C Family Development Chronicle
C Language Quick Start (1) HelloWorld
C Language Quick Start (2) Basic Data Types
C Language Quick Start (3) Pointer Types
Arrays
Arrays are ordered collections of variables of the same data type stored in contiguous memory.
Orderliness : Memory addresses increase sequentially from the first to the last element.
Indexable : Elements are accessed by zero‑based indices.
Defining an Array
An array definition consists of three parts:
Array name : Represents the address of the first element.
Type : All elements share the same data type.
Length : Number of elements, fixed at compile time in C/C++.
int aArray[5] = {1, 2, 3, 4, 5};
int bArray[5] = {0};
for (int i = 0; i < 5; i++) {
bArray[i] = aArray[i]; // NOTE: only one element can be assigned at a time; bArray = aArray is illegal.
}Because C/C++ does not perform automatic bounds checking, developers must manually verify that indices stay within the array limits to avoid undefined behavior.
The following example deliberately accesses out‑of‑bounds indices; the compiler does not report an error, highlighting the need for explicit checks.
#include <stdio.h>
int main(void) {
int i, j;
int aArray[5] = {1, 2, 3, 4, 5};
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
aArray[i * 5 + j] = i * 5 + j;
printf("aArray[%d]=%d
", i * 5 + j, aArray[i * 5 + j]);
}
}
return 0;
}Running the above code produces out‑of‑range values and eventually a segmentation fault.
aArray[0]=0
aArray[1]=1
...
aArray[24]=24
Segmentation faultA corrected version adds a bounds check before writing:
int main(void) {
int i, j, idx;
int aArray[5] = {1, 2, 3, 4, 5};
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
idx = i * 5 + j;
if (idx > sizeof(aArray) / sizeof(int)) {
printf("Err: idx over range!
Max idx=%lu, Current idx=%d
", sizeof(aArray) / sizeof(int), idx);
return 0;
}
aArray[idx] = idx;
printf("aArray[%d]=%d
", idx, aArray[idx]);
}
}
return 0;
} aArray[0]=0
aArray[1]=1
...
aArray[4]=4
Err: idx over range!
Max idx=5, Current idx=6Initializing Arrays
Specify length : The initializer must not contain more elements than the declared length.
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};Omit length : The compiler deduces the length from the number of initializer elements.
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};Accessing Array Elements
Elements are accessed using the array name followed by an index.
Read: double salary = balance[3]; Write:
balance[4] = 50.0;Multidimensional Arrays
C supports multidimensional arrays. The general declaration is:
type name[size1][size2]...[sizeN];
int threedim[5][10][4];Two‑dimensional arrays are the most common:
Initializing a 2‑D Array
int a[3][4] = {
{0, 1, 2, 3}, // row 0
{4, 5, 6, 7}, // row 1
{8, 9, 10, 11} // row 2
};
// or flat initializer
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};Accessing a 2‑D Element
int val = a[2][3];Pointer Arrays
A pointer array stores pointers as its elements.
#include <stdio.h>
const int MAX = 3;
int var[] = {10, 100, 200};
int *ptr[MAX]; // array of int pointers
for (int i = 0; i < MAX; i++) {
ptr[i] = &var[i]; // assign address of each int
}
for (int i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d
", i, *ptr[i]);
}
return 0;Array Pointers
Two related concepts:
Array name : a constant pointer to the first element; cannot be modified.
Array pointer variable : a mutable pointer that can be reassigned to point to an entire array.
Array Name
The array name is equivalent to &balance[0]. It can be used directly or via pointer arithmetic, e.g., *(balance + 4).
double balance[50] = {};Difference Between &array and &array[0]
int array[4] = {0};
printf("array = %p
", array);
printf("&array = %p
", &array);
printf("&array[0] = %p
", &array[0]);
printf("array + 1 = %p
", array + 1);
printf("&array + 1 = %p
", &array + 1);
printf("&array[0] + 1 = %p
", &array[0] + 1);
printf("sizeof(int) = %lu
", sizeof(int));
printf("sizeof(array[0]) = %lu
", sizeof(array[0]));
printf("sizeof(array) = %lu
", sizeof(array));
printf("sizeof(&array) = %lu
", sizeof(&array));
printf("sizeof(&array[0]) = %lu
", sizeof(&array[0])); array = 0x7ffeecd8c830
&array = 0x7ffeecd8c830
&array[0] = 0x7ffeecd8c830
array + 1 = 0x7ffeecd8c834
&array + 1 = 0x7ffeecd8c840
&array[0] + 1 = 0x7ffeecd8c834
sizeof(int) = 4
sizeof(array[0]) = 4
sizeof(array) = 16
sizeof(&array) = 8
sizeof(&array[0]) = 8Array Pointer Variable
Using a mutable pointer variable allows pointer arithmetic, unlike the constant array name.
#include <stdio.h>
const int MAX = 3;
int var[] = {10, 100, 200};
int *ptr = var; // copy array name to pointer variable
for (int i = 0; i < MAX; i++) {
printf("Address: var[%d] = %p
", i, ptr);
printf("Value: var[%d] = %d
", i, *ptr);
ptr++; // move to next element (4 bytes for int)
}
return 0; Address: var[0] = 0x7ffe48f272d0
Value: var[0] = 10
Address: var[1] = 0x7ffe48f272d4
Value: var[1] = 100
Address: var[2] = 0x7ffe48f272d8
Value: var[2] = 200Decrementing works similarly in reverse order.
#include <stdio.h>
const int MAX = 3;
int var[] = {10, 100, 200};
int *ptr = &var[MAX - 1]; // point to last element
for (int i = MAX; i > 0; i--) {
printf("Address: var[%d] = %p
", i-1, ptr);
printf("Value: var[%d] = %d
", i-1, *ptr);
ptr--; // move backward
}
return 0; Address: var[2] = 0x7ffdbab78f88
Value: var[2] = 200
Address: var[1] = 0x7ffdbab78f84
Value: var[1] = 100
Address: var[0] = 0x7ffdbab78f80
Value: var[0] = 10Passing an Array to a Function
A function can receive an array by declaring a parameter as a pointer, an array with a fixed size, or an unsized array.
int arr[10] = {};
void myFunction(int *param) {}
void myFunction(int param[10]) {}
void myFunction(int param[]) {}Example that computes the average of an integer array:
#include <stdio.h>
double getAvg(int arr[], int size) {
double sum = 0;
for (int i = 0; i < size; ++i) {
sum += arr[i];
}
return sum / size;
}
int main() {
int balance[5] = {1000, 2, 3, 17, 50};
double avg = getAvg(balance, 5);
printf("AVG: %f
", avg);
return 0;
}Returning an Array Pointer from a Function
C functions cannot return whole arrays, but they can return a pointer to an array (often a static array).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int* getRandom() {
static int r[10];
srand((unsigned)time(NULL));
for (int i = 0; i < 10; i++) {
r[i] = rand();
printf("r[%d] = %d
", i, r[i]);
}
return r;
}
int main() {
int *p = getRandom();
for (int i = 0; i < 10; i++) {
printf("*(p + %d): %d
", i, *(p + i));
}
return 0;
}Strings
C does not have a dedicated string type; a string is a character array terminated by a null character '\0'.
char greeting[6] = {'H','e','l','l','o','\0'};Using a string literal is more readable; the compiler adds the terminating null automatically.
char greeting[] = "Hello";String Manipulation Functions
C provides a set of standard library functions for handling strings.
Copying and Length
strcpy()
Copies a null‑terminated source string to a destination buffer.
char *strcpy(char *dst, const char *src);strlen()
Returns the number of characters in a null‑terminated string, excluding the terminator.
size_t strlen(const char *str);Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s
", str3);
strcat(str1, str2);
printf("strcat( str1, str2): %s
", str1);
int len = strlen(str1);
printf("strlen(str1) : %d
", len);
return 0;
} strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10String Comparison
strcmp()
int strcmp(const char *src, const char *dst);Compares two strings lexicographically; returns 0 if equal, a positive value if the first string is greater, and a negative value if it is smaller.
strncmp()
int strncmp(const char *src, const char *dst, size_t n);Compares up to n characters, providing safer comparison when strings may have different lengths.
Example comparing "ABCDHG" and "ABCDEF":
strncmp(str1, str2, 4) // returns 0
strncmp(str1, str2, 5) // returns 1When comparing strings of unequal length, specifying n ensures only the intended characters are examined, avoiding false mismatches caused by leftover buffer data.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
