← Back to quizzesFree quiz

Pointers and Strings in C

Understanding pointers and strings is essential for mastering the C programming language. This course breaks down the most frequently tested ideas, explains why they matter, and provides…

10 questions~5 min
Pointers and Strings in C — Qwi
0 / 10
Score: 0%
1

What is the effect of the statement `*ptr_var = 4;` after `short var = 3; short* ptr_var = &var;`?

2

Given `short* ptr_tab = tab;` where `short tab[3];`, what does `ptr_tab` point to?

3

In the function `calc_carre(short* var){ short x = *var; *var = x * x; }`, what will be printed after calling `calc_carre(&test);` with `test` initially equal to 2?

4

Which of the following statements correctly allocates memory for an array of 6 `long` values?

5

What will `strlen(prenom)` return if `char* prenom = "Arnaud";`?

6

If `char* nom = "Guillemard";` what does `strchr(nom,'l')` return?

7

What is the primary risk of using a pointer that has not been assigned a valid address before dereferencing it?

8

Which function must be called after `malloc` to avoid memory leaks?

9

In the pointer arithmetic example, why does `ptr_short++` change the address by 2 bytes?

10

When using `scanf("%s", nom);` to read a word into `char* nom` allocated with `malloc(sizeof(char))`, what is the most likely outcome?

Pointers and Strings in C: Core Concepts and Common Pitfalls

Understanding pointers and strings is essential for mastering the C programming language. This course breaks down the most frequently tested ideas, explains why they matter, and provides clear examples that you can copy‑paste into your own programs. By the end of the lesson you will be able to read, write, and debug pointer‑related code with confidence.

1. Basic Pointer Dereferencing

Consider the following declaration:

short var = 3;
short *ptr_var = &var;

The statement *ptr_var = 4; does not modify the pointer itself. Instead, it accesses the memory location that ptr_var points to and writes the value 4 there. After execution, var becomes 4 while ptr_var still holds the address of var.

  • Key takeaway: The asterisk (*) before a pointer variable is the dereference operator. It turns a pointer into the actual object it points to.
  • Common mistake: Confusing *ptr_var = 4; with ptr_var = 4;. The latter would attempt to assign a new address to the pointer, which is usually a compile‑time error unless the address is a valid pointer.

2. Pointers to the First Element of an Array

When you write:

short tab[3];
short *ptr_tab = tab;

the identifier tab automatically decays to a pointer to its first element. Therefore ptr_tab points to tab[0], not to the whole array object.

  • Why it matters: Functions that accept short * parameters can work with any contiguous block of short values, including arrays, dynamically allocated memory, or even a single variable.
  • Tip: Use sizeof(tab) / sizeof(tab[0]) to compute the number of elements only when you still have the original array name; once it decays to a pointer the size information is lost.

3. Modifying a Variable Through a Pointer

Take the function:

void calc_carre(short *var) {
    short x = *var;   // read the current value
    *var = x * x;     // write the square back
}

If short test = 2; and you call calc_carre(&test);, the function reads 2, computes 2 * 2 = 4, and stores 4 back into test. Consequently, printing test after the call yields 4.

  • Lesson: Passing the address of a variable lets a function modify the original value, a technique known as “call‑by‑reference”.
  • Remember: The pointer itself is passed by value; the function receives a copy of the address, not the original pointer variable.

4. Dynamic Memory Allocation for Arrays

To allocate space for six long values you must request 6 * sizeof(long) bytes:

long *ptr_tab = (long *)malloc(sizeof(long) * 6);

Using malloc(6) would only reserve six bytes, which is far too small on most platforms (a long is typically 4 or 8 bytes). The correct pattern is:

  1. Determine the size of one element with sizeof(type).
  2. Multiply by the number of elements you need.
  3. Cast the returned void * to the appropriate pointer type (optional in C, mandatory in C++).

Memory‑leak prevention: After you finish using the allocated block, always call free(ptr_tab); to return the memory to the system.

5. Measuring String Length with strlen

The function strlen counts characters up to, but not including, the terminating null byte (\0). For the literal:

char *prenom = "Arnaud";

the string contains six printable characters (A r n a u d), so strlen(prenom) returns 6.

  • Analogy: Think of the string as a staircase; strlen counts the steps without counting the door that closes the staircase (the null terminator).
  • Quick test: strlen("Bob") yields 3 because the three letters are counted before the hidden \0.

6. Locating Characters with strchr

When you call:

char *nom = "Guillemard";
char *ptr = strchr(nom, 'l');

strchr returns a pointer to the first occurrence of the character 'l'. In this example the returned pointer points to the substring "llemard". If the character is not found, the function returns NULL.

  • Use case: You can iterate through a string by repeatedly calling strchr with the pointer returned from the previous call + 1.
  • Safety tip: Always test the result against NULL before dereferencing.

7. Dangers of Uninitialized Pointers

Dereferencing a pointer that has never been assigned a valid address leads to undefined behavior. The program may crash, corrupt memory, or appear to work correctly on some runs and fail on others.

Think of an uninitialized pointer as a GPS device with no coordinates – it can send you anywhere, including dangerous or inaccessible locations.

  • Best practice: Initialize pointers to NULL and check for NULL before dereferencing.
  • Debugging aid: Tools like Valgrind or AddressSanitizer can detect reads/writes through invalid pointers.

8. Releasing Dynamically Allocated Memory

Every successful call to malloc, calloc, or realloc should be paired with a call to free when the memory is no longer needed. Failing to do so creates a memory leak, which over time can exhaust the available RAM and cause the program to terminate unexpectedly.

long *ptr_tab = (long *)malloc(sizeof(long) * 6);
/* use the array */
free(ptr_tab);   // release the memory
ptr_tab = NULL;  // avoid dangling pointer
  • Remember: After calling free, the pointer becomes a dangling pointer; setting it to NULL prevents accidental reuse.
  • Performance note: Frequent allocations and deallocations can fragment the heap; consider allocating once and reusing the buffer when possible.

9. Quick Review Quiz

Test your knowledge with the following multiple‑choice questions. The correct answers are highlighted in bold.

  1. What does *ptr_var = 4; do after short var = 3; short *ptr_var = &var;?
    • It changes the pointer to point to a new memory address.
    • It increments the address stored in ptr_var by 4 bytes.
    • It creates a new variable with value 4.
    • It changes the value of var to 4.
  2. Given short* ptr_tab = tab; where short tab[3];, what does ptr_tab point to?
    • The first element of tab.
    • The address of the array object tab itself.
    • The last element of tab.
    • A null pointer.
  3. What will be printed after calling calc_carre(&test); with test initially equal to 2?
    • "test = 8"
    • "test = 4"
    • "test = 2"
    • "test = 0"
  4. Which statement correctly allocates memory for an array of 6 long values?
    • ptr_tab = (long *) malloc(sizeof(long));
    • ptr_tab = (long *) malloc(6);
    • ptr_tab = (long *) malloc(sizeof(long)*6);
    • ptr_tab = (long *) malloc(sizeof(long)); ptr_tab = ptr_tab + 6;
  5. What will strlen(prenom) return if char* prenom = "Arnaud";?
    • 5
    • 7
    • 6
    • 0
  6. If char* nom = "Guillemard"; what does strchr(nom,'l') return?
    • Pointer to the first 'l' in "Guillemard" ("llemard").
    • Pointer to the last 'l' in the string.
    • NULL, because 'l' is not in the string.
    • Pointer to the character after the first 'l'.
  7. What is the primary risk of using a pointer that has not been assigned a valid address before dereferencing it?
    • The program will compile but not run.
    • The pointer will be set to zero.
    • Undefined behavior due to accessing random memory.
    • The pointer will automatically allocate memory.
  8. Which function must be called after malloc to avoid memory leaks?
    • calloc
    • delete
    • free
    • realloc

10. Practical Exercises

Try implementing the following snippets on your own machine. Compile with gcc -Wall -Wextra -pedantic to catch common mistakes.

  1. Write a function swap_int(int *a, int *b) that exchanges the values of two integers using only pointer operations.
  2. Allocate an array of 10 char using malloc, fill it with the word "HelloWorld", then print the length using strlen. Remember to free the memory.
  3. Given a string char *s = "abracadabra";, use strchr in a loop to count how many times the letter 'a' appears.

By mastering these concepts you will be equipped to handle most pointer‑related interview questions and to write robust, memory‑safe C programs.