2
#include<iostream>

using namespace std;



int main(){

char s[10] = "abcde"; 

char* first = s - 1;

cout << first << endl;

return 0;
}

when I run this, I get a blank in my console, but when I say *first = s; I get the whole char array printed to my console. My question is, what exactly is first pointing to when I set it to s - 1?

2
  • 2
    char* first = s - 1 points to garbage? Commented Jul 2, 2013 at 1:30
  • 1
    This is UB. The reason you're seeing the whole array is because you forgot to add \0 at the end of the string. Commented Jul 2, 2013 at 1:31

2 Answers 2

4

When you set a pointer to s-1, the pointer points to a character at a position in memory that is one char before your allocated string. Dereferencing such pointer is undefined behavior - the program may print anything, or even crash.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2510809 Correct - undefined behavior is a wrong thing to do. Programs that invoke undefined behavior are considered invalid.
0

first would point to a piece of unallocated memory - the behavior is undefined

Comments

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.