简体   繁体   中英

Unable to understand the output in C++ Pointers. (Working with loops in pointers)

Unable to understand the unexpected output. The pointer doesn't point to the 0th index no. of a string

I have been trying to find the reason for the output of the following program. the loop starts from i=0 but there is no character being displayed at the 0th index no. and the loop starts from the 1st index no.

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

I am getting the following output: liceicecee But I expected the output to start from 'A'.

You should really upgrade to a modern compiler. There are many free ones available.

#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
}

If you want to print the letters one by one (using your current program as a base) using standard 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
}

What strlen does is to search for the first \\0 character and to count how long it had to search. You really don't need to do that here since you are going through all the characters (by stepping x ) yourself. Illustration:

#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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM