Emanuele Pavanello
Emanuele Pavanello

Reputation: 863

Array of static char* 's

I would like to know if it is correct C++ :

static char *arrayExample[]  = 
{
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h"
};

Upvotes: 1

Views: 692

Answers (2)

Baltasarq
Baltasarq

Reputation: 12212

I would like to know if is correct write that in C++

static char *arrayExample[]  = 
{
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h"
};

Does it compile even if you don't add the const modifier? Yes, but it is misleading. String literals are stored in memory area in which all string literals of the source code are saved, one after another. This means that you should not mess with it (in a PC it won't happen. but it could be mapped to ROM memory).

So, it is basically correct. However, this array of literals is not meant to be modified, so you should better rewrite it to be:

static const char *arrayExample[]  = 
{
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h"
};

You have declared it to be static: this means that it will only be visible in its own translation unit (i.e. the very cpp file in which it was created). If that's what you intended (you did not intend to be able to share it among translation units), then it is perfectly okay.

Hope this helps.

Upvotes: 5

Déjà vu
Déjà vu

Reputation: 28840

If you try to compile with -Wall the compiler warns you

warning: deprecated conversion from string constant to ‘char*’

An array of "x" constant strings makes the initialization of the array, while the declaration is only

static char *

This is not wrong per say, but you may try to modify an item of the array like

*arrayExample[2] = 'x'; // runtime error / crash / undefined behavior

Adding const removes the compiler warning(s), and prevents you from writing some code that would overwrite the read-only values, which would compile, but would crash at runtime. const will have the compiler stops with an error (not a warning) when trying to overwrite one of the char * item of the array.

static const char *

Upvotes: 0

Related Questions