-3

I'm trying to dereference this pointer to a new array (ARR) , but from this example below when i do the derefencing *issub it only "carries" the first letter. How can i fix this situation and have ARR(subscount) be the word i want?

#include <iostream>
  int main(){
  char inp[3]={'O','I','L'};
  int lll=3;
  char ARR[3];
  int subscount=0;

  char * issub= new char[lll];
  for(int i=0;i<lll;i++){
    issub[i]=inp[i];
  }
  ARR[subscount]=*issub;
 }
gsamaras
  • 71,951
  • 46
  • 188
  • 305
J. Barbosa
  • 21
  • 6

1 Answers1

1

I feel that you are confused, so I made an example for you:

#include <iostream>

int main() {
  char inp[4] = {'O','I','L', '\0'};
  int lll = 4;
  // initialize elements of 'ARR' to 0 for safety
  char ARR[4] = {0};
  int subscount = 0;

  // dynamic allocation, DO NOT forget to de-allocate
  char* issub = new char[lll];
  // copy every element of 'inp' to 'issub'
  for(int i=0;i<lll;i++) {
    issub[i]=inp[i];
  }
  // this will copy where '*issub' points to,
  // that is the 'issub[0]', to 'ARR[subscount]'
  ARR[subscount] = *issub;
  std::cout << ARR << "\n"; // prints: O
  // you can use a for loop as before to copy the contents,
  // from 'inp', 'issub' to 'ARR'

  // However, we will do something different here,
  // so I am de-allocating 'issub'
  delete [] issub;

  // We will use an array of pointers, with size 2,
  // thus it will have two pointers in total.
  char* ptr_arr[2];

  // Assign the first pointer to 'inp'
  ptr_arr[0] = &(inp[0]);

  std::cout << ptr_arr[0] << "\n"; // prints OIL

  // we don't use the second pointer,
  // set it to NULL
  ptr_arr[1] = NULL;
  return 0;
}

Hope that helps (but it really reminds me of C, rather than C++, where std::string should be used).


Updated with a null terminated string; What is a null-terminated string?

Thanks @M.M

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305