C++ C+中的指针算法和数组+;

C++ C+中的指针算法和数组+;,c++,C++,我尝试创建一个新的字符数组,并向其中添加字符。我想用指针来做。我知道通过指针算法可以移动数组中的指针,所以我想使用它。但是它不起作用,我也不知道为什么。知道为什么我不能在数组中使用指针算术吗 #include <math.h> #include <iostream> using namespace std; void print (char *k){ while(*k!=0)cout<<*k++; } int main(){ int max

我尝试创建一个新的字符数组,并向其中添加字符。我想用指针来做。我知道通过指针算法可以移动数组中的指针,所以我想使用它。但是它不起作用,我也不知道为什么。知道为什么我不能在数组中使用指针算术吗

#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);  

}
#包括
#包括
使用名称空间std;
无效打印(字符*k){

而(*k!=0)不能这是非常复杂的

*++temp1 = 0;
*--temp1 = ch;
temp1++;
惯用的方式是:

*temp1++ = ch;
*temp1 = 0;
但最重要的是
print(temp1);
是错误的,因为
temp1
不指向字符串,而是指向字符串的末尾

你想要这个:

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);
}
或者更简单:

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);
}

这是非常复杂的

*++temp1 = 0;
*--temp1 = ch;
temp1++;
惯用的方式是:

*temp1++ = ch;
*temp1 = 0;
但最重要的是
print(temp1);
是错误的,因为
temp1
不指向字符串,而是指向字符串的末尾

你想要这个:

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);
}
或者更简单:

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);
}

问题是指针算法确实有效。因此,您无法打印字符串,因为指针不再指向数组的开头。您需要一个始终指向数组开头的指针,以及另一个向数组添加字符的指针。问题是指针算法确实有效。因此,无法打印字符串,因为指针不再指向数组的开头。您需要一个始终指向数组开头的指针,以及另一个向数组添加字符的指针。更简单的是,删除
new
char s[128]{};char*p=s;/*../print(s)更简单的是,删除
新的
chars[128]{};char*p=s;/*..*/print;