Mike32ab
Mike32ab

Reputation: 466

Can you find the length of a string from an array of pointers to strings?

Can you find the length of a string by doing subtraction on an array of pointers to strings? For example if I have the code below

char *pStrings[4] = {
    "First string",
    "Hello",
    "Afternoon",
    "Ab"
};

int firstStrLen = pStrings[1] - pStrings[0] - 1; //Will I get the length of the first string by doing this?

Will firstStrLen be the length of the first string?

Upvotes: 0

Views: 75

Answers (3)

FredK
FredK

Reputation: 4084

Here's an example that shows what @dasblinkenlight and @MByD were saying.

char*s1 = "Hello";
char *pStrings[4] = {
    "First string",
    "Hello",
    "Afternoon",
    "Ab"
};

In the above code, the compiler may (and probably will) point s1 and pStrings[1] to the same location, which may be nowhere near where pStrings[0] points. So even if the subtraction were legal (it is not), your method would not work.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

No, this is undefined behavior.

You are allowed to subtract pointers only when they are pointing to memory from the same contiguous memory block. In your example pStrings[1] and pStrings[0] are not pointing to a contiguous block of memory, so the result of pStrings[1] - pStrings[0] is undefined.

6.5.6.9: When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

Upvotes: 6

MByD
MByD

Reputation: 137412

No. There is no guarantee that the strings will be located next to each other in the memory.

Upvotes: 3

Related Questions