C Programming

Strings in C; Pointers in C

C-CAT

Strings in C

What are Strings?

In C, a string is an array of characters terminated by a null character '\0'.

char str[] = "Hello";   // Stored as: ['H','e','l','l','o','\0']
// OR
char str[6] = {'H','e','l','l','o','\0'};

String Declaration

char str1[] = "Hello";             // size = 6 (5 chars + '\0')
char str2[20] = "World";           // can hold up to 19 chars
char str3[20];                     // uninitialized
char *str4 = "Literal string";     // string literal (read-only!)

String Operations

#include <stdio.h>
#include <string.h>

int main() {
    char str1[50] = "Hello";
    char str2[50] = "World";
    char result[100];

    // Length
    printf("Length of str1: %zu\n", strlen(str1));     // 5

    // Copy
    strcpy(result, str1);   // result = "Hello"

    // Concatenate
    strcat(result, " ");
    strcat(result, str2);
    printf("Concatenated: %s\n", result);               // Hello World

    // Compare
    int cmp = strcmp(str1, str2);
    if (cmp == 0) printf("Equal\n");
    else if (cmp < 0) printf("str1 < str2\n");          // This prints ('H' < 'W')
    else printf("str1 > str2\n");

    // Search for substring
    char *found = strstr(result, "World");
    if (found) printf("Found 'World' at: %s\n", found);  // World

    // Find character
    char *ch = strchr(str1, 'l');
    if (ch) printf("First 'l' at index: %ld\n", ch - str1);  // 2

    // String to number
    char numstr[] = "42";
    int n = atoi(numstr);         // "42" → 42
    float f = atof("3.14");       // "3.14" → 3.14

    return 0;
}

String Input/Output

// Safe string input with fgets
char name[100];
printf("Enter name: ");
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';  // remove trailing newline
printf("Hello, %s!\n", name);

// sprintf — format string into char array
char buffer[100];
int age = 25;
sprintf(buffer,
"Age is %d years", age);
printf("%s\n", buffer);   // Age is 25 years

// sscanf — parse from string
char data[] = "42 3.14";
int x;
float y;
sscanf(data, "%d %f", &x, &y);
printf("x=%d, y=%.2f\n", x, y);   // x=42, y=3.14

Common String Functions

FunctionDescriptionExample
strlen(s)Length of string (excludes '\0')strlen("Hello") = 5
strcpy(dst, src)Copy src to dststrcpy(d, "Hi")
strncpy(dst,src,n)Copy at most n charsSafe version of strcpy
strcat(dst, src)Append src to dststrcat(s, "!")
strncat(dst,src,n)Append at most n charsSafe version
strcmp(s1, s2)Compare; return 0 if equalstrcmp("Hi","Hi")==0
strncmp(s1,s2,n)Compare first n chars
strchr(s, c)Find first occurrence of cstrchr("Hello",'l') → "llo"
strstr(s, sub)Find first occurrence of substrstr(s,"ell") → "ello"
strtok(s, delim)Tokenize stringSplit by delimiters
atoi(s)String to intatoi("42") = 42
atof(s)String to floatatof("3.14") = 3.14
toupper(c)Char to uppercasetoupper('a')='A'
tolower(c)Char to lowercasetolower('A')='a'
isalpha(c)Is alphabetic?isalpha('a')=1
isdigit(c)Is digit?isdigit('9')=1

Pointers in C

What is a Pointer?

A pointer is a variable that stores the memory address of another variable.

int x = 42;
int *ptr = &x;    // ptr stores the address of x

printf("Value of x: %d\n", x);           // 42
printf("Address of x: %p\n", (void*)&x); // 0x7ffd12345678 (some address)
printf("Value of ptr: %p\n", (void*)ptr);// 0x7ffd12345678 (same address)
printf("Dereference ptr: %d\n", *ptr);   // 42 (value at the address)

Operators:

  • & — address-of operator: gives address of a variable
  • * — dereference operator: gives value at the address

Pointer Declaration

int *p;         // pointer to int
float *fp;      // pointer to float
char *cp;       // pointer to char
void *vp;       // generic pointer (can point to any type)
int **pp;       // pointer to pointer (double pointer)

Why Use Pointers?

  1. Pass by reference — modify caller's variables from a function
  2. Dynamic memory — malloc/calloc returns pointers
  3. Arrays — array name is a pointer to first element

Data structures — linked lists, trees, graphs use pointers 5. Function pointers — pass functions as arguments

Pointer and Arrays

int arr[] = {10, 20, 30, 40, 50};
int *p = arr;   // p points to arr[0]

// These are equivalent:
printf("%d\n", arr[0]);   // 10
printf("%d\n", *p);       // 10
printf("%d\n", p[0]);     // 10
printf("%d\n", *(arr+0)); // 10

printf("%d\n", arr[2]);   // 30
printf("%d\n", *(p+2));   // 30
printf("%d\n", p[2]);     //
30

// Traverse array using pointer
for (int *ptr = arr; ptr < arr + 5; ptr++) {
    printf("%d ", *ptr);
}
// Output: 10 20 30 40 50

Pointer to Pointer

int x = 10;
int *p = &x;     // p → x
int **pp = &p;   // pp → p → x

printf("x = %d\n", x);     // 10
printf("*p = %d\n", *p);   // 10
printf("**pp = %d\n",
**pp); // 10

**pp = 99;  // modify x through double pointer
printf("x = %d\n", x);     // 99

NULL Pointer

int *p = NULL;   // pointer not pointing to anything

// ALWAYS check for NULL before dereferencing!
if (p != NULL) {
    printf("Value: %d\n",
*p);
} else {
    printf("Null pointer!\n");
}

// Dereferencing NULL causes segmentation fault (crash)
// *p = 5;  // CRASH: segfault!

Continue learning

Related notes

Put this topic into timed practice

Open mock tests when you want full-exam pacing, or keep drilling in practice mode.