0

I tried to make a new char array and add to it chars. I wanted it to do by pointer. I know that is possible to move pointers in array by pointer arithmetic , so I wanted to use it. However it doesn't work and I don't know really why. Any idea why i can't use pointer arithemtic in array?

#include <math.h>
#include <iostream>
using namespace std;
void print (char *k){
 
  while(*k!=0)cout<<*k++;

}

int main(){

   int max = 128;
   char* temp1 = new char[max];
   *temp1 = 0;
   char ch;
   while (cin.get(ch)) {
        if (ch=='\n') break;
        *++temp1 = 0;
        *--temp1 = ch;
        temp1++;
      
  }
  
  print(temp1);  

}
1
  • 1
    The problem is that pointer arithmetic did work. And as a result, you can't print the string because the pointer no longer points to the beginning of the array. You need one pointer that always points to the beginning of the array, and another pointer to add characters to the array. Commented Mar 18, 2021 at 7:46

1 Answer 1

2

This is very convoluted

*++temp1 = 0;
*--temp1 = ch;
temp1++;

The idiomatic way would be this:

*temp1++ = ch;
*temp1 = 0;

But most importantly print(temp1); is wrong, because temp1 does not point to the string but it points to the end of the string.

You want this:

int main() {
  int max = 128;
  char* thestring = new char[max];
  char* temp1 = thestring;
  *temp1 = 0;
  char ch;
  while (cin.get(ch)) {
    if (ch == '\n') break;
    *temp1++ = ch;
    *temp1 =0;
  }

  print(thestring);
}

or even simpler:

int main() {
  int max = 128;
  char* thestring = new char[max];
  char* temp1 = thestring;
  char ch;
  while (cin.get(ch)) {
    if (ch == '\n') break;
    *temp1++ = ch;
  }

  *temp1 = 0;

  print(thestring);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Even simpler, remove the new: char s[128]{}; char* p = s; /*..*/ print(s);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.