## Is there an algorithm to compress a string array represented as pointers to a long string to pointers with a compressed version of the long string?

In a program I am writing, I represent an array of strings as a long string and have pointers point at the various substrings to present my array. E.g.

``str_array = struc string_array    long_str = "abcdefab"    pointer_array = [(start = 0, len = 3), (start = 3, len = 3), (start = 6, len=2)) end ``

So `str_array = ["abc", "def", "ab"]`, but notice that I can actually compress the long string so by getting rid of “ab” at the end. E.g.

``str_array2 = struc string_array    long_str = "abcdef"    pointer_array = [(start = 0, len = 3), (start = 3, len = 3), (start = 0, len=2)) end ``

and note that `str_array2` is also `["abc", "def", "ab"] === str_array`.

What’s this type of compresssion callled in computer science? I assume there’s already literature on this type of algorithms?

## How do I print Node pointers so that I can debug in C++? [on hold]

I’m trying to solve this problem and I would like to know how to output the values inside of the *Node object so that I can debug it. I don’t really know much about C++. I come from a JavaScript background and would like to know more about how JS works under the hood so I’m studying CS concepts.

https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=trees&h_r=next-challenge&h_v=zen

I tried this…

``    Node *lca(Node *root, int v1,int v2) {         cout << *root->data;         cout << v1;         cout << v2;         return 0;     } ``

but I keep getting seg fault errors (and I have no idea what that means.)

Could someone explain in excruciating detail what I’m doing wrong?

## C++ Factory for Polymorphism + Templates + Smart Pointers

I’m trying to build a Factory class so I can:

``Builder* x_builder = BuilderFactory::create("X"); vector<unique_ptr<XItem>> x_items; x_builder->build(&x_items);  Builder* y_builder = BuilderFactory::create("Y"); vector<unique_ptr<YItem>> y_items; y_builder->build(&y_items); ``

Currently I have:

``template <typename T> class Builder {     virtual void build(vector<unique_ptr<T>>* out) = 0; }  class XBuilder : public Builder<XItem> {     void build(vector<unique_ptr<XItem>>* out) override; }  class YBuilder : public Builder<YItem> {     void build(vector<unique_ptr<YItem>>* out) override; } ``

But I can’t do this since the Factory won’t be able to create a Builder* without specifying the template type.

I’ve tried returning the vector instead of passing in as an argument, and set XItem and YItem as subclasses of BaseItem, since normally covariant return types would allow me to return subclassed types. Unfortunately covariant return types do not work with smart pointers.

I can also do this without templates, and just have two separate non-override methods for build like:

``class Builder { }  class XBuilder : public Builder<XItem> {     void build(vector<unique_ptr<XItem>>* out); }  class YBuilder : public Builder<YItem> {     void build(vector<unique_ptr<YItem>>* out); } ``

But with this, I won’t be able to `(Builder*)->build(...)` anymore.

Can I get some ideas please on how to design for this Factory? Thanks

## Binary Search in C – Pointers and Memory

I got a warning when I am returning “list” in the function createList “Address of stack memory associated with local variable ‘list’ returned”

I am confused about pointers and memory allocation and not sure how to fix it. int* createList(int quantity){ int list[quantity];

``printf("Please enter a list of numbers\n"); for(int i = 0 ; i < quantity ; i++){     scanf("%i",&list[i]); } return list;}   int findNumber(int number){     printf("Please chose a number\n");     scanf("%i",&number);     return number; }    int main() {     int quantity;     printf("How many numbers do you want?\n");     scanf("%i",&quantity);     return 0; } ``

## c++ smart shared pointer for both pointers and non pointer types

I created this shared pointer mainly to use it as RAII for handles that have to be shared between classes or threads

for pointers : it supports raw pointers and pointer to classes and arrays and also support classes inheriting from ref_base class to save an allocation for the reference counter

for non pointers types : they must be nullable and aren’t arrays or inheriting from ref_base

this is my code :

``#include <atomic> #include <type_traits> #include <Windows.h>  using namespace std;  #define HAS_TYPE(NAME) \ template<typename, typename = void> \ struct has_type_##NAME: std::false_type \ {}; \ template<typename T> \ struct has_type_##NAME<T, void_t<typename T::NAME>>: std::true_type \ {} \  HAS_TYPE(pointer);   template <class T, bool is_it_array = false> struct default_sp_deleter {     void operator()(T *ptr)     {         delete ptr;     } };  template <class T> struct default_sp_deleter<T, true> {     void operator()(T *ptr)     {         delete[] ptr;     } };  template <class T, class D, bool inherit, bool has_pointer> struct sp_data {};  template <class T, class D> struct sp_data<T, D, true, true> {     using pointer = typename D::pointer;     pointer ptr;     D deleter;     sp_data() : ptr(pointer())     {}     sp_data(pointer p) : ptr(p)     {}     sp_data(pointer p, D del) : ptr(p), deleter(del)     {} };  template <class T, class D> struct sp_data<T, D, true, false> {     using pointer = T*;     pointer ptr;     D deleter;     sp_data() : ptr(pointer())     {}     sp_data(pointer p) : ptr(p)     {}     sp_data(pointer p, D del) : ptr(p), deleter(del)     {} };  template <class T, class D> struct sp_data<T, D, false, false> {     using pointer = T*;     pointer ptr;     D deleter;     atomic<uintptr_t> *ref_count;     sp_data() : ptr(pointer()), ref_count(new atomic<uintptr_t>(0))     {}      sp_data(pointer p) : ptr(p), ref_count(new atomic<uintptr_t>(0))     {}      sp_data(pointer p, D del) : ptr(p), deleter(del), ref_count(new atomic<uintptr_t>(0))     {}      sp_data(const sp_data<T, D, false, false>& data) : ptr(data.ptr), ref_count(data.ref_count)     {}      ~sp_data()     {}      sp_data& operator=(const sp_data<T, D, false, false>& data)     {         ptr = data.ptr;         ref_count = data.ref_count;         return *this;     }  };  template <class T, class D> struct sp_data<T, D, false, true> {     using pointer = typename D::pointer;     pointer ptr;     D deleter;     atomic<uintptr_t> *ref_count;     sp_data() : ptr(pointer()), ref_count(new atomic<uintptr_t>(0))     {}      sp_data(pointer p) : ptr(p), ref_count(new atomic<uintptr_t>(0))     {}      sp_data(pointer p, D del) : ptr(p), deleter(del), ref_count(new atomic<uintptr_t>(0))     {}      sp_data(const sp_data<T, D, false, false>& data) : ptr(data.ptr), ref_count(data.ref_count)     {}      template     <class U>     sp_data(const sp_data<U, D, false, false>& data) : ptr(data.ptr)     {      }      ~sp_data()     {}      sp_data& operator=(const sp_data<T, D, false, false>& data)     {         ref_count = data.ref_count;         ptr = data.ptr;         return *this;     } };  class ref_base;  template <class T, class Deleter =  default_sp_deleter<typename std::remove_all_extents<T>::type, std::is_array<T>::value>> class sp {      using elem_type = typename std::remove_all_extents<T>::type;      using pointer = typename sp_data<elem_type, Deleter, std::is_base_of<ref_base, T>::value, has_type_pointer<Deleter>::value>::pointer;      sp_data<elem_type, Deleter, std::is_base_of<ref_base, pointer>::value, has_type_pointer<Deleter>::value> data;  public :      using element_type = typename std::remove_pointer_t<pointer>;      template<typename, typename> friend class sp;      sp()     {}      sp(pointer p)     {         data.ptr = p;         if (get() != pointer())             inc_ref();     }      sp(const sp<T, Deleter>& rhs) : data(rhs.data)     {         if (get() != pointer())             inc_ref();     }      sp(sp<T, Deleter>&& rhs) : data(rhs.data)     {         rhs.data.ptr = pointer();     }      template     <class U>     sp(const sp<U, Deleter>& rhs) : data(rhs.data)     {         if (get() != pointer())             inc_ref();     }      template     <class U>     sp(sp<U, Deleter>&& rhs) : data(rhs.data)     {         rhs.data.ptr = pointer();     }      template     <class U, typename std::enable_if<std::is_convertible<U, pointer>::value && !std::is_same<U, pointer>::value, bool>::type = true>      sp(U value)     {         data.ptr = value;         if (get() != pointer())             inc_ref();     }      ~sp()     {         reset();     }      sp<T, Deleter>& operator=(const sp<T, Deleter>& rhs)     {         reset();         data = rhs.data;         if (get() != pointer())             inc_ref();         return *this;     }      sp<T, Deleter>& operator=(sp<T, Deleter>&& rhs)     {         reset();         data = rhs.data;         if (get() != pointer())             inc_ref();         rhs.reset();         return *this;     }      template     <class U>     sp<T, Deleter>& operator=(const sp<U, Deleter>& rhs)     {         reset();         data = rhs.data;         if (get() != pointer())             inc_ref();         return *this;     }      template     <class U>     sp<T, Deleter>& operator=(sp<U, Deleter>&& rhs)     {         reset();         data = rhs.data;         if (get() != pointer())             inc_ref();         rhs.reset();         return *this;     }      pointer get() const     {         return data.ptr;     }      template     <class U = pointer>      typename std::enable_if<is_pointer<U>::value, element_type&>::type     operator*()     {         return *data.ptr;     }      template     <class U = pointer>     typename std::enable_if<!std::is_pointer<U>::value, pointer&>::type operator&()     {         return &data.ptr;     }       pointer operator->()     {         return get();     }      long use_count()     {         if (get() == pointer())             return 0;         return private_use_count();     }      bool unique()     {         return use_count() == 1;     }      operator bool()     {         return get() != pointer();     }      Deleter& get_deleter()     {         return data.deleter;     }      void reset(pointer ptr = pointer())     {         if (get() == ptr)             return;          if (has_counter() && !dec_ref())         {             get_deleter()(get());         }          release_ref_counter();          data.ptr = ptr;         if (get() != pointer())         {             setup_counter();             inc_ref();         }     }  private :      template<class U = element_type>     typename enable_if<is_base_of<ref_base, U>::value && std::is_pointer<pointer>::value>::type inc_ref()     {         get()->inc_ref();     }      // currently this type of members is broken and shouldn't be used :     // if Deleter::pointer exists it mustn't inherit from ref_base      template<class U = element_type>     typename enable_if<is_base_of<ref_base, U>::value && !std::is_pointer<pointer>::value>::type inc_ref()     {         data.ptr.inc_ref();     }      template<class U = element_type>     typename enable_if<!is_base_of<ref_base, U>::value>::type inc_ref()     {         ++(*data.ref_count);     }      template<class U = element_type>     typename std::enable_if<std::is_base_of<ref_base, U>::value && std::is_pointer<pointer>::value, uintptr_t>::type dec_ref()     {         return get()->dec_ref();     }      template<class U = element_type>     typename std::enable_if<std::is_base_of<ref_base, U>::value && !std::is_pointer<pointer>::value, uintptr_t>::type dec_ref()     {         return data.ptr.dec_ref();     }      template<class U = element_type>     typename std::enable_if<!std::is_base_of<ref_base, U>::value, uintptr_t>::type dec_ref()     {         --(*data.ref_count);         return data.ref_count->load();     }      template<class U = element_type>     typename std::enable_if<std::is_base_of<ref_base, U>::value && std::is_pointer<pointer>::value, uintptr_t>::type private_use_count()     {         return get()->use_count();     }      template<class U = element_type>     typename std::enable_if<std::is_base_of<ref_base, U>::value && !std::is_pointer<pointer>::value, uintptr_t>::type private_use_count()     {         return data.ptr.use_count();     }      template<class U = element_type>     typename std::enable_if<!std::is_base_of<ref_base, U>::value, uintptr_t>::type private_use_count()     {         return data.ref_count->load();     }      template<class U = element_type>     typename std::enable_if<std::is_base_of<ref_base, U>::value>::type release_ref_counter()     {}      template<class U = element_type>     typename std::enable_if<!std::is_base_of<ref_base, U>::value>::type release_ref_counter()     {         if (data.ref_count && !(*data.ref_count))         {             delete data.ref_count;         }         data.ref_count = nullptr;     }      template<class U = element_type>     typename std::enable_if<std::is_base_of<ref_base, U>::value>::type setup_counter()     {}      template<class U = element_type>     typename std::enable_if<!std::is_base_of<ref_base, U>::value>::type setup_counter()     {         data.ref_count = new atomic<uintptr_t>(0);     }      template<class U = element_type>     typename std::enable_if<std::is_base_of<ref_base, U>::value, bool>::type has_counter()     {         return get() != pointer();     }      template<class U = element_type>     typename std::enable_if<!std::is_base_of<ref_base, U>::value, bool>::type has_counter()     {         return data.ref_count != nullptr;     }  };   class ref_base {  public :      template<typename, typename> friend class sp;      ref_base() : ref_count(0)     {}      ref_base(const ref_base&) : ref_count(0)     {}      ref_base(ref_base&&) : ref_count(0)     {}      ~ref_base()     {}      ref_base& operator=(const ref_base&)     {         return *this;     }      ref_base& operator=(ref_base&&)     {         return *this;     }   private :         uintptr_t inc_ref()     {         ++ref_count;         return ref_count.load();         }      uintptr_t dec_ref()     {         --ref_count;         return ref_count.load();     }      long use_count()     {         return ref_count.load();     }      atomic<uintptr_t> ref_count; };  class test : public ref_base {     public :      test()      {}      ~test()      {          cout << "~test()" << endl;      }  };  class test2 { public :     test2()     {}      ~test2()     {         cout << "~test2()" << endl;     } };  template <typename T, T TNul = T(), bool pseudo = false> class UniqueHandle { public:      UniqueHandle(std::nullptr_t = nullptr)         :m_id(TNul)     { }      UniqueHandle(T x)         :m_id(x)     {         // if file handle but not process or thread one prevent -1         if (!pseudo && m_id == INVALID_HANDLE_VALUE)             m_id = TNul;     }     explicit operator bool() const { return m_id != TNul; }      operator T&() { return m_id; }     operator T() const { return m_id; }      T *operator&() { return &m_id; }     const T *operator&() const { return &m_id; }      friend bool operator == (UniqueHandle a, UniqueHandle b) { return a.m_id == b.m_id; }     friend bool operator != (UniqueHandle a, UniqueHandle b) { return a.m_id != b.m_id; }     friend bool operator == (UniqueHandle a, std::nullptr_t) { return a.m_id == TNul; }     friend bool operator != (UniqueHandle a, std::nullptr_t) { return a.m_id != TNul; }     friend bool operator == (std::nullptr_t, UniqueHandle b) { return TNul == b.m_id; }     friend bool operator != (std::nullptr_t, UniqueHandle b) { return TNul != b.m_id; }  private:     T m_id; };  template <class HandleType, class DeleterType, DeleterType Deleter, HandleType null_handle = HandleType(), bool pseudo = false> struct UniqueHandleDeleter {     using pointer = UniqueHandle<HandleType, null_handle, pseudo>;     void operator()(pointer handle)     {         if (pseudo)         {             // pseudo handle is valid but isn't to be closed             if (handle == pointer(GetCurrentProcess()))                 return;         }         Deleter(handle);     } };  using SHandle = sp<int, UniqueHandleDeleter < HANDLE, decltype(&CloseHandle), CloseHandle>>; using SProcHandle = sp<int, UniqueHandleDeleter<HANDLE, decltype(&CloseHandle), CloseHandle, nullptr, true>>; using SRegHandle = sp<int, UniqueHandleDeleter<HKEY, decltype(&RegCloseKey), RegCloseKey>>; using SSocket = sp<int, UniqueHandleDeleter<SOCKET, decltype(&closesocket), closesocket, -1>>; ``

## Creating pointers to keys on SmartCard

I am new to OpenPGP and SmartCards but I cannot find how to do a fairly straight-forward task.

I am trying to sign a file with a private key stored on a YubiKey device.

Here is my session:

``\$   gpg --card-status Reader ...........: Yubico Yubikey 4 OTP U2F CCID 00 00 Application ID ...: D2760001240102010006096334120000 Version ..........: 2.1 Manufacturer .....: Yubico Serial number ....: 09633412 Name of cardholder: [not set] Language prefs ...: [not set] Sex ..............: unspecified URL of public key : [not set] Login data .......: [not set] Signature PIN ....: not forced Key attributes ...: rsa2048 rsa2048 rsa2048 Max. PIN lengths .: 127 127 127 PIN retry counter : 3 0 3 Signature counter : 3 Signature key ....: B692 4360 F06A AB92 1B9A  3E6D 3850 24E1 EE26 F6D9   created ....: 2019-05-14 14:44:27 Encryption key....: [none] Authentication key: B692 4360 F06A AB92 1B9A  3E6D 3850 24E1 EE26 F6D9   created ....: 2019-05-14 14:44:27 General key info..: [none] \$   \$   gpg -K \$   \$   gpg --list-keys \$   \$   gpg --with-subkey-fingerprint -K \$   \$   gpg --refresh-keys \$   gpg --list-keys \$   ``

I looked at some posts like this one: Create backup Yubikey with identical PGP keys but I am still not sure what I am doing wrong.

All I need to is somehow use the signature key to sign a file via

``gpg --sign -u <key-id> somefile.txt ``

I need to somehow create a pointer in my local keyring to the Signature key and figure out its id.

I am using gpg (GnuPG) 2.2.12 and libgcrypt 1.8.4

Any suggestions?

## Is it an ok practice to keep pointers dereferenced?

For me, I prefer having all my variables, not as pointers. Is it ok to keep all heap-allocated variables dereferenced?

For example:

``#include "Foo.hpp" #include "Bar.hpp"  class Foo { private:  Bar* ptr = new Bar(); }; ``

Would it be ok to have Bar as a dereferenced pointer, without causing any issues?

Example:

``Bar b = *(new Bar()); ``

## Do parent pointers affect path-copying in a persistent binary tree?

I am familiar with the concept of path-copying in the context of binary trees to achieve persistent modifications, but I am unsure if the inclusion of parent pointers has any effect on the complexity. We can assume that rotations may occur, so for practical consideration we can assume an AVL or red-black tree.

My current thought process is that “when a node is modified, anything that points to that node must also be copied”. If that theory is correct, and we therefore copy every node along the path from the root to the node, what happens when we do rotations along the path? My intuition is that nodes on the path are the only ones modified, but I am worried that the sibling node that is not on the path might also need to be copied. I would guess that that is not the case, but I am struggling to confirm that.

Does the existence of parent pointers affect the number of nodes to be copied during a modification in a persistent binary tree?

## Calculate power of number with pointers? [on hold]

I am practicing pointers in C. I tried to make function which will calculate power of given numbers, but I tried to do that with pointers. I read that it is possible to put pointer of value on every place where it is possible to put integer, but something in my code is not correct and I cannot see what, everything seems logical to me:

``#include <stdio.h> #include <stdlib.h>  int powerPointer(int *arg1, int *arg2){  int i; int *result = 1;  for(i=0; i<*arg2; i++){     *result = *result * *arg1;     return *result; } }    int main() { int a, b; printf("First argument a: "); scanf("%d", &a); printf("Second argument b: "); scanf("%d", &b); int res = powerPointer(&a, &b); printf("Result a^b is: %d", res);  return 0; ``

## Storing inherited specialized templated types into a vector of shared pointers?

I’m working on a Register class that will be used in a virtual pc application. I’m trying to make them as basic and as fast as possible so they should be trivially default constructible and trivially default copyable at the least.

My register types will rely on typedefs for their types:

Register.h

``#pragma once  #include <vector> #include <memory>  typedef std::uint8_t u8; typedef std::uint16_t u16; typedef std::uint32_t u32; typedef std::uint64_t u64;  struct Register {     virtual void* getValue() = 0; };  template<typename T> struct Register_ty : Register {     void* data_;     explicit Register_ty(T* data) : data_(data) {}      virtual void* getValue() = 0; };  template<typename T> struct Register_t : Register_ty<T> {};  template<> struct Register_t<u8> : Register_ty<u8> {     explicit Register_t(u8* data) : Register_ty<u8>( data ) {}     void* getValue() override {         return data_;     } };  template<> struct Register_t<u16> : Register_ty<u16> {     explicit Register_t(u16* data) : Register_ty<u16>(data) {}     void* getValue() override {         return data_;     } };  template<> struct Register_t<u32> : Register_ty<u32> {     explicit Register_t(u32* data) : Register_ty<u32>(data) {}     void* getValue() {         return data_;     } };  template<> struct Register_t<u64> : Register_ty<u64> {     explicit Register_t(u64* data) : Register_ty<u64>(data) {}     void* getValue() {         return data_;     } };  struct Memory {     std::vector<Register*> bank; // vector };  ``

And when I go to use it as such:

``#include <iostream> #include "Register.h"  int main() { u8 a = 8; Register_t<u8> r8(&a);  u16 b = 16; Register_t<u16> r16(&b);  u32 c = 32; Register_t<u32> r32(&c);  u64 d = 64; Register_t<u64> r64(&d);  Memory mem; mem.bank.push_back( &r8 ); mem.bank.push_back( &r16 ); mem.bank.push_back( &r32 ); mem.bank.push_back( &r64 );  for (auto& b : mem.bank) {     std::cout << b->getValue() << '\n'; }      return EXIT_SUCCESS; } ``

Everything at this point seems okay and it gives me a possible output of:

``000000000029F6B4 000000000029F704 000000000029F754 000000000029F7A8 ``

Which is giving me the address of the pointers. However when I try to dereference them as such:

``for ( auto& b : mem.bank ) {     std::cout << *b->getValue() << '\n'; } ``

This fails to compile so I had to go back and rethink my code… I came up with this so far:

``#include <iostream> #include "Register.h"  int main() {     using namespace vpc;      u8* pa = nullptr;     u8 a = 8;     pa = &a;     Register_t<u8> r8(pa);      u16* pb = nullptr;     u16 b = 16;     pb = &b;     Register_t<u16> r16(pb);      u32* pc = nullptr;     u32 c = 32;     pc = &c;     Register_t<u32> r32(pc);      u64* pd = nullptr;     u64 d = 64;     pd = &d;     Register_t<u64> r64(pd);      Memory mem;     mem.bank.push_back( &r8 );     mem.bank.push_back( &r16 );     mem.bank.push_back( &r32 );     mem.bank.push_back( &r64 );      for (auto& b : mem.bank) {         std::cout << b->getValue() << '\n';     }      std::cout << '\n';      for (auto& b : mem.bank) {         auto p = b->getValue();         auto res = reinterpret_cast<u8*>(p);          std::cout << static_cast<u16>(*res) << '\n';     }     return EXIT_SUCCESS; }; ``

And it has given me the output of:

``00000000001DF694 00000000001DF704 00000000001DF774 00000000001DF7E8  8 16 32 64 ``

Which is now giving me the correct values. This is the first time I was able to achieve this behavior and I had to use `pointer manipulation` to do it. Originally I wasn’t using pointers at all and I wasn’t using `void*` in my classes.

Then I couldn’t just create a variable and pass it by its address as that wasn’t working either so I had to create variables of those types in my main code and initialize them with something, I had to create pointers of those types and initialize them with `nullptr`, and finally I had to assign my pointers to their respective variable type addresses.

Then to be able to retrieve the actual values from these pointers by dereferencing them I had to do some pointer manipulation by casting then I had to cast that dereferenced type.

``for (auto& b : mem.bank) {     // create an auto p and get the value; p should be a void*     auto p = b->getValue();      // create an auto type for our result and cast our     // void* p to a u8* {smallest type} and {char} based     auto res = reinterpret_cast<u8*>(p);      // now since the underlying type is char I have to deference my     // res* and static cast it to a u16.      std::cout << static_cast<u16>(*res) << '\n'; } ``

This bit of hack isn’t very pretty or friendly. It works so far however I can already see some issues ahead of time. If I have a Register that is of a u64 type and it has a majority of its bits filled with data that is needed and I reinterpret its pointer to a u8*, dereference that and cast that to a u16 type I’m going to lose information, however this is the only combination that it provided me with the correct results.