DEV Community

Wacim Chelly
Wacim Chelly

Posted on

2

Understanding char** in C/C++

In C and C++, char** is a pointer to a pointer of type char. It is commonly used to represent arrays of strings, such as command-line arguments (argv), dynamic arrays of strings, or 2D arrays where each row is a string. Though initially confusing, with some examples, you’ll see how it operates similarly to handling a "table of strings."

What is char* *?
A char* is a pointer to a char, representing a single string.
A char** is a pointer to a char*, which means it points to an array of strings (or an array of char* pointers).

Example:

#include <stdio.h>

int main() {
    char* strings[] = {"I love", "Embedded", "Systems"};

    // Create a char** pointer to the strings array
    char** string_ptr = strings;

    // Access and print the strings using char**
    for (int i = 0; i < 3; i++) {
        printf("%s\n", string_ptr[i]);
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Breakdown:

  • char* strings[]: Declares an array named strings, with each element pointing to a character (a char*), essentially forming an array of strings.
  • {"I love", "Embedded", "Systems"}: Initializes the strings array with string literals stored in memory as character arrays. The compiler converts these literals into char* pointers, assigned to the array elements.

Visual Representation:

Main Index (char**) → String 1 (char*) → "I love"
                   → String 2 (char*) → "Embedded"
                   → String 3 (char*) → "Systems"
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • strings is an array of pointers to strings, not an array of characters.
  • Each element of the array points to the first character of a string literal.
  • You can manipulate individual characters within the strings using pointer arithmetic or array indexing.

Conclusion:

  • char** is a pointer to an array of strings, much like a "table of strings."
  • Memory is allocated separately for each string (row), allowing you to work with each string individually.
  • Functions can modify the contents of the strings because char** passes a reference to the original array of pointers.

Working with char** is powerful when handling dynamic arrays, command-line arguments, or multi-dimensional arrays of strings in C/C++. Once you understand its structure, it simplifies the process of managing arrays of strings in your programs.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More