-2

Code

I came across this question while practicing pointer questions, and, according to my understanding, I thought option C would be correct, but Option D was the correct answer, so I ran the code in Visual Studio Code and it did give a compilation error.

Strings are terminated by a NULL character. Then why is an error occurring if the for loop is checking for the occurrence of the NULL character?

Error message

What is the problem with this code? Here is the actual code:

#include<iostream>
using namespace std;

int main() {
  char st[] = "ABCD";
  for(int i = 0; st[i] != ‘\0’; i++) {
     cout << st[i] << *(st)+i << *(i+st) << i[st];
  }
  return 0;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KUMAR HARSH
  • 95
  • 1
  • 10
  • 3
    From [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): "_**DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question_" – Ted Lyngmo Feb 27 '21 at 09:34
  • It is the wrong close reason. It should be closed as a duplicate of the canonical question *[Compilation error: stray ‘\302’ in program, etc.](https://stackoverflow.com/questions/19198332/)*. – Peter Mortensen May 04 '23 at 18:46
  • Not all errors are shown here, but from what is: 342 200 231 (octal) → 0xE2 0x80 0x98 (hexadecimal) → UTF-8 sequence for Unicode code point U+2019 ([RIGHT SINGLE QUOTATION MARK](https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8212&number=128)). – Peter Mortensen May 04 '23 at 18:46
  • This is a ***very*** common error when copying code from web pages, [PDF](https://en.wikipedia.org/wiki/Portable_Document_Format) documents, through chat (e.g. [Skype Chat](https://en.wikipedia.org/wiki/Features_of_Skype#Skype_chat) or [Facebook Messenger](https://en.wikipedia.org/wiki/Facebook_Messenger)), etc. The canonical question is *[Compilation error: stray ‘\302’ in program, etc.](https://stackoverflow.com/questions/19198332)*. – Peter Mortensen May 04 '23 at 18:47

1 Answers1

3

(U+2018 LEFT SINGLE QUOTATION MARK) and (U+2019 RIGHT SINGLE QUOTATION MARK) are Unicode characters, and your source file is saved in UTF-8.

You likely copied this code from some website which used these characters.

You need to use ASCII ' (U+0027 APOSTROPHE) instead:

st[i] != '\0'
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • 1
    thanks after using ' problem was solved and code ran perfectly – KUMAR HARSH Feb 28 '21 at 09:50
  • They can be searched for (and replaced) by using the regular expression `\x{2018}|\x{2019}` in any modern text editor or IDE (note: The notation is different in Visual Studio Code (and probably others): `\u2018|\u2019` (instead of `\x{2018}|\x{2019}`)). – Peter Mortensen May 04 '23 at 18:44