conterio
conterio

Reputation: 1174

c++ store address of next position of the array

I have an array that I want to store the address of the next array in the current position.

So far I have

char *a = new char[50];
char *free = a;

*a = &(a + 1); //value of a[0] is equal to the address of a[1] 

Also I'm using a char array so I'm sure I'll need to cast some stuff.
Any help would be nice.

Upvotes: 1

Views: 173

Answers (1)

xforever1313
xforever1313

Reputation: 91

You can't store a char* in a char array.

A character is equal to one byte. The size of a pointer, such as char*, varies depending on your computer. On my computer, its 8 bytes. 8 bytes can't fit in 1 byte.

#include <iostream>

int main()
{
    std::cout << "sizeof(char): " << sizeof(char) << std::endl;
    std::cout << "sizeof(char*): " << sizeof(char*) << std::endl;
    return 0;
}

// Outputs 
// sizeof(char): 1
// sizeof(char*): 8

You also won't be able to cast a char* to a char to fit it in the array either, as your compiler will yell at you.

#include <iostream>

int main()
{
    char myArray[10];
    std::cout << (char)&myArray[0];
}

// Compiler error:
// g++ main.cpp -std=gnu++11
// main.cpp: In function ‘int main()’:
// main.cpp:7:34: error: cast from ‘char*’ to ‘char’ loses precision [-fpermissive]

The closest thing you can do to get this working is to use an array of size_t. size_t is the size of a pointer. So the number of bytes in size_t and size_t* is equal, and therefore you can put a size_t* in an array of size_t... after casting.

#include <iostream>

int main()
{
    size_t myArray[10];
    myArray[0] = reinterpret_cast<size_t>(&myArray[1]);

    std::cout << std::hex << "0x" << myArray[0] << std::endl;
}
// Outputs: 0x7fff4eded5c8

Also, consider using indicies[] instead of pointer addition. Its more readable, and it does the same thing under the hood. a[1] == *(a+1).

Upvotes: 3

Related Questions