Constant string arrays

Is it possible to have a (fixed) array that stores its elements in a read-only segment of an executable file, and not on the stack? I came up with this code, but unfortunately it is very inflexible when it comes to adding, moving or deleting elements. How to check if rows are really stored in a read-only segment? I tried the readelf -a file, but it does not list the lines.

typedef struct {
        int len;
        int pos[100];
        char data[500];
} FixedStringArray;

const FixedStringArray items = {
        4,
        { 9, 14, 19, 24 },
        "LongWord1Word2Word3Word4"
} ;

char* GetItem(FixedStringArray *array, int idx, int *len) {
        if (idx >= array->len) {
                /* Out of range */
                *len = -1;
                return NULL;
        }

        if (idx > 0) {
                *len = array->pos[idx] - array->pos[idx - 1];
                return & array->data[array->pos[idx - 1]];
        }

        *len = array->pos[idx];
        return & array->data[0];
}

void PrintItem(FixedStringArray array, int idx) {
        int len;
        char *c;
        int i = 0;

        c = GetItem(&array, idx, &len);

        if (len == -1) return;

        while (i < len) {
                printf("%c", *c);
                *c++;
                i++;
        }
}

I am considering a script that automatically generates a structure for each array and uses the correct length for pos and data. Are there any problems in terms of memory usage? Or would it be better to create one structure (e.g. above) to match all rows?

+5
3

, , :

const char * const array[] = { "LongWord1", "Word2", "Word3", "Word4" };

.

, strlen, :

struct Str {
    size_t len;
    char *str;
};
#define STR(s) { sizeof(#s) - 1, #s }
const struct Str[] = { STR(LongWord1), STR(Word2), STR(Word3), STR(Word4) };
+23

C / (, V++ )? , ?

+1

:

, ROM/RAM /, . script . .

0

All Articles