Skip to study material
← Question index

QUESTION 32 · String Basics

Explain character pointers and const string parameters in functions.

5 marks

Answer in brief

A character pointer can identify the first byte of a string. Functions can use it to read characters or, for a writable target and suitable interface, modify them.

Read-only interface

void show(const char *text);

Working

The caller supplies a pointer to the first character. show reads text until its null terminator through puts. The const-qualified character access prevents the function from writing text[0] through this parameter. The local pointer parameter itself is a copied pointer value.

String literal and array

A literal such as "Welcome" must not be modified. A writable array such as char name[] = "Student"; contains its own copy and can be changed within bounds. Both can be passed to a suitable reading function. Use const char * for a literal pointer so the intended reading-only use is clear.

Modification interface

A function that writes a string normally needs char * and a destination capacity. The pointer alone does not communicate how many positions are available. A function must not store beyond the capacity or leave a result unterminated when a string result is promised.

Return and lifetime

Returning a pointer is valid only when the target remains alive for its later use. Do not return the address of an ordinary automatic local character array. A pointer to caller-owned storage or a suitable lasting object requires a clearly stated lifetime and ownership agreement.

Complexity

Displaying n bytes takes O(n) output work. The pointer argument is small fixed-size state and does not copy the whole string. No new variable-length buffer is created by this example.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void show(const char *text)
{
    puts(text);
}

int main(void)
{
    show("Welcome");
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Welcome

Related exam questions

Related questions in the string basics category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September 2023 · Q4(a) · 5 marks

    Differentiate a null-terminated string and a fixed-length string.

    Paper P06 · page 1
  • January/February 2024 · Q4(b) · 6 marks

    Compare character arrays and string literals. Explain strings as arrays of characters.

    Paper P08 · page 1

View this category in the exam question bank →