0

I wondered how char sequence(string) arranged in RAM, so make below testing with c++. The compiler environment is 64bit system, cygwin on windows10.

#include <iostream>

using namespace std;

int main() {

    char* c1 = "01";
    cout << "string to print:" << endl;
    cout << c1 << endl;
    cout << "the address in stack of the pointer:" << endl;
    cout << &c1 << endl;
    cout << "the address in heap for the first letter in the string:" << endl;
    cout << (void*)c1 << endl;
    cout << "the address in heap for the second letter in the string:" << endl;
    cout << (void*)(++c1) << endl;
}

output is:

string to print:
01
the address in stack of the pointer:
0xffffcc28
the address in heap for the first letter in the string:
0x100403001
the address in heap for the second letter in the string:
0x100403002

I recognize that the address of char '0' and '1' just offset 1byte. So is that mean the two chars just arrange one by one in one ram unit? As below illustration?

/*
 *    64bit ram
 *         |-------------------------64bits--------------------------------|
 *   stack |                                                               |
 *
 *   heap  | 8bits | 8bits | 8bits | 8bits | 8bits | 8bits |  '1'  |  '0'  |
 */
Machi
  • 403
  • 2
  • 14
  • 4
    `char* c1 = "01";` is **not valid C++**. You should instead write it as `const char* c1 = "01";` – Jason Dec 14 '21 at 10:28
  • 6
    "char '0' and '1' just offset 1bit" your image shows that they are offset by 1byte not 1bit – 463035818_is_not_an_ai Dec 14 '21 at 10:29
  • 2
    Have a read of https://en.cppreference.com/w/cpp/language/string_literal including _"...Whether string literals can overlap and whether successive evaluations of a string-literal yield the same object is unspecified. That means that identical string literals may or may not compare equal when compared by pointer...."_ . So any testing is unique to your environment / tool-chain. – Richard Critten Dec 14 '21 at 10:35
  • sizeof(char) always = 1 in C, I'm sure I could find C++ stuff if I looked at more than 1/2 the search results. I googled "sizeof(char) always 1" – enhzflep Dec 14 '21 at 10:49
  • 1
    Essentially correct, except that the string literal is not stored on "the heap". There is also some "static" memory, for objects that live all through the program execution. https://stackoverflow.com/questions/408670/stack-static-and-heap-in-c – BoP Dec 14 '21 at 11:55
  • I just corrected a type mistake. The offset is one byte not one bit. Sorry for making confuse. @enhzflep – Machi Dec 15 '21 at 02:17

1 Answers1

1

I recognize that the address of char '0' and '1' just offset 1bit.

No. They are offset one byte. The size of char is one byte and array elements are adjacent in virtual memory. String is an array.

eerorika
  • 232,697
  • 12
  • 197
  • 326