无法理解C ++指针中的输出。(使用指针中的循环)

Abh*_*dey 3 c++ pointers

无法理解意外的输出。指针没有指向第0个索引号。一串

我一直在尝试寻找以下程序输出的原因。循环从i = 0开始,但是在第0个索引编号处没有显示字符。循环从第一个索引编号开始。

#include <conio.h>
#include <iostream.h>
#include <string.h>

int main() 
{
  clrscr();

  int i, n;
  char *x = "Alice";
  n = strlen(x);
  *x = x[n];

  for (i = 0; i <= n; i++) 
  {
    cout << x;
    x++;
  }

  cout << endl << x;
  getch();
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:liceicecee 但是我希望输出从'A'开始。

Ted*_*gmo 6

您应该真正升级到现代编译器。有许多免费的。

#include <iostream.h> // non-standard header file
#include <string.h>   // not recommended - it brings its functions into the global namespace

void main() { // main must return "int"
    int i, n;
    char* x = "Alice"; // illegal, must be const char*
    n = strlen(x);
    *x = x[n]; // illegal copy of the terminating \0 to the first const char

    for(i = 0; i <= n; i++) { // <= includes the terminating \0
        cout << x; // will print: "", "lice", "ice", "ce", "e", ""
                   // since you move x forward below
        x++;
    }
    cout << endl << x; // x is now pointing after the \0, undefined behaviour
}
Run Code Online (Sandbox Code Playgroud)

如果要使用标准C ++一次打印字母(以当前程序为基础):

#include <iostream>
#include <cstring>

int main() {
    const char* x = "Alice";
    size_t n = std::strlen(x);

    for(size_t i = 0; i < n; ++i, ++x) {
        std::cout << *x; // *x to dereferece x to get the char it's pointing at
    }
    std::cout << "\n"; // std::endl is overkill, no need to flush
}
Run Code Online (Sandbox Code Playgroud)

什么strlen是搜索第一个\0字符并计算必须搜索多长时间。您实际上不需要在这里执行此操作,因为您x自己(通过逐步)会经历所有角色。插图:

#include <iostream>

int main() {
    const char* x = "Alice";
    size_t n = 0;

    while(*x != '\0') {
        std::cout << *x;
        ++x;
        ++n;
    }
    std::cout << "\nThe string was " << n << " characters long\n";
}
Run Code Online (Sandbox Code Playgroud)