edited by
728 views
2 votes
2 votes
char buffer[6]=”hello”;
char *prt1=buffer -1; /* undefined behavior */
char *ptr2 = buffer +5;  /*Ok, pointing to the ‘\0’ inside the array */
char *ptr3 = buffer +6;  /* OK, pointing to just beyond */
char *ptr4 = buffer +7;  /* undefined behavior */

Please clear last two line.. and why 2nd last is not undefined behavior.

edited by

2 Answers

Best answer
5 votes
5 votes
char buffer[6]=”hello”;
char *prt1=buffer -1; /* undefined behavior */
char *ptr2 = buffer +5;  /*Ok, pointing to the ‘\0’ inside the array */
char *ptr3 = buffer +6;  /* OK, pointing to just beyond */
char *ptr4 = buffer +7;  /* undefined behavior */

char *ptr3 = buffer + 6 is valid, as we are allowed to legally point to one past the last array element until we dereference it .

Actually, Setting a pointer one past the last element of an array is allowed in C and C++. 

Hence, setting to pointer after '\0' ends in an array is allowed for only one position .

Ex => char buffer[8] = "vijaycs"

so, buffer + 7 returns '\0' which is surely allowed .

and Setting a pointer to  buffer + 8(one past the last array element) is also valid, until it is dereferenced like

buffer[8] or *(buffer + 8), as it is not legal to access the contents of an address outside the allocated memory for an array.

Hence, after this setting a pointer to buffer + 9 and onwards is undefined behaviour .

You can read more here => https://gcc.gnu.org/onlinedocs/libstdc++/manual/iterators.html

selected by

Related questions

1 votes
1 votes
1 answer
1
jugnu1337 asked May 10, 2022
260 views
SOURCE NAME::: UNDERSTANDING POINTER IN C (BOOK) BY YASHWANT KANETKARmy answer is C am i right?
1 votes
1 votes
0 answers
2
aakash pandey asked Apr 30, 2022
281 views
We use character array to declare string in C. So, if I declare an array likecharacter ch[ ] = {‘a’,’k’,’a’,’/o’};and try printing ch[3] like :printf(“%...
0 votes
0 votes
0 answers
3
Anirudh Kaushal asked Apr 6, 2022
191 views
#include<stdio.h struct marks { int p:3; int c:3; int m:2; }; void main() { struct marks s = {2, -6, 5}; printf("%d %d %d", s.p, s.c, s.m); }What does p:3 means here ?
0 votes
0 votes
0 answers
4