samuelbrody1249
samuelbrody1249

Reputation: 4767

Array index equivalent with a pointer

If I have:

char    str2[]  = "Word2";

What is the equivalent of doing:

str2[1] = 'a';

My thought was the following but it seems like this is pretty overkill:

(
 // part 3 -- cast memory address (int) as pointer
 * (char *)
 // part 1 -- get the memory address as an int
 ((long)&str2
 // part 2 -- get the index of 1 by +1 memory address
 +1)
) = 'a';

Upvotes: 1

Views: 89

Answers (1)

swag2198
swag2198

Reputation: 2696

The declaration

char str2[] = "word2";

sets the name str2 as an array type to the first byte of consecutive memory locations storing the string "word2", particularly str2 will point to a byte in memory storing the character w. (However note that, str2 is not a pointer, see the comments below.)

Note that if you now try to dereference str2 + 1, which follows pointer arithmetic, the pointer will be incremented by the size of the data type of the element being pointed at, which here is of char type and hence address pointed by str2 + 1 will be precisely 1 byte (size of char data type) away from the address pointed by str. Thus, str2 + 1 will point to the memory byte having 'o'.

Your seemingly overkill code

( // part 3 -- cast memory address (int) as pointer * (char *) // part 1 -- get the memory address as an int ((long)&str2 // part 2 -- get the index of 1 by +1 memory address +1) ) = 'a';

works because is char is of size 1 byte and hence the +1 part takes the pointer to the next byte which is also the next character in the string. Had it been an integer array, you would have to increment by 4 or 8 bytes (depending on the size of int in your system) to get to the next element of the array.

The equivalent code segments for whatever you are trying to achieve are already in the comments by dxiv. I just wanted to clarify things a bit.

Upvotes: 1

Related Questions