TCPL 5.9.9 (C ++): Where would it be appropriate to use the name in your own initializer?

This is a question from the latest version of Stroustrup "C ++ Programming Language".

I have been pondering this in my head for the last couple of days.

The only thing I can think of, (and this is probably wrong), looks something like this:

int* f(int n) {
  int* a = &a - n * sizeof(int*);
  return a;
}

My intention is to get the address of something higher in the stack. Does that make sense? Does anyone have any other answers? Remember that this is in chapter 5 (pointers, arrays, and structures), so the answer should not include something later in the book.

+3
source share
5 answers

( ) , , - . , , node:

class Node
{
public:
    Node(Node* next): next(next) {}
private:
    Node* next;
};

. :

Node n(&n);

, (.. , ), :

int n = sizeof(n);
void* p = &p;
+3

, C:

C *c = (C*) malloc(sizeof *c);
...
free(c);

. , new , new C ++.

+4

, . :)

-, sizeof, n a. , , .

int*  a = &a - n; // so if n==1 => a = &a - (1*4)
char* b = &b - n; // so if n==1 => b = &b - (1*1)

-, .

, , - :)

0

-, , . , , ( , ). , , , ( , , ..), "" , .

?

0

, :

// clang++ --std=c++11 initializer.cpp -o initializer

#include <iostream>

using namespace std;

void Print(int* array) {
    cout << "array has " << *array << " elements" << endl;
    for(int count {*array}; count; --count) {
        cout << *++array << endl;
    }
}

int main(int, char* []) {
    {
        int elements[] {sizeof(*elements), 1, 2, 3};
        *elements = sizeof(elements) / *elements - 1;
        Print(elements);
    }
    cout << "---" << endl;
    {
        int elements[] {sizeof(*elements)};
        *elements = sizeof(elements) / *elements - 1;
        Print(elements);
    }
    return 0;
}

:

./initializer                                                                                                                                                                                                     
array has 3 elements
1
2
3
---
array has 0 elements

P.S. GitHub: 8: 9.3

0

Source: https://habr.com/ru/post/1713509/


All Articles