Unexpected C code output - c

This is my c code:
#include <stdio.h>
int main(){
int x[] = {6,1,2,3,4,5};
int *p=0;
p =&x[0];
while(*p!='\0'){
printf("%d",*p);
p++;
}
return 0;
}
When run the output is 612345-448304448336
What are the digits after the minus sign and why is my code giving this?

The condition *p != '\0', which is the same as *p != 0, is never met because your array doesn't contain an element of value 0, and thus you overrun the array bounds and step into undefined behaviour.
Instead, you should control the array range directly:
for (int const * p = x; p != x + sizeof(x)/sizeof(x[0]); ++p) // or "p != x + 6"
{
printf("%d", *p);
}

You run the loop till you encounter a \0 but your array was never \0 terminated.
int x[] = {6,1,2,3,4,5};
creates an array which is not \0 terminated. You will have to explicitly add a \0 as the last element.
Since the array is not \0 terminated the while() loops run until a random \0 is encountered. Technically, this is Undefined Behavior because you are reading the contents of memory which is not allocated to your variable.
Suggested Solution:
int x[] = {6,1,2,3,4,5,0};
while(*p != 0)

Arrays in C are not Null Terminated. Which is why your loop goes beyond the end of your declared array. The digits follows 5 are just whatever happens to be in that memory space. If there hadn't been a null character following your allocation of the array the loop would have continued running until it made a SegFault.

Related

Why the code get executed twice?

I am trying to write code for reverse polish notation calculator. Why when I input a number the following code gets executed twice ?
int a[50];
int topOfStack = -1;
char c;
while((c = getchar()) != EOF)
{
int n = atoi(&c);
topOfStack += 1;
a[topOfStack] = n;
printf("top of stack is %d\n", a[topOfStack]);
printf("index top of stack is %d\n", topOfStack);
}
return 0;
}
This
int n = atoi(&c);
is undefined behavior.
The atoi() function takes a char * pointer pointing to a string, AKA a sequence of non-nul bytes followed by a nul byte.
You are passing a pointer to a single char, then atoi() increments the pointer trying to find the terminating '\0' but dereferencing the incremented pointer is undefined behavior because the pointer does not point to an array.
When there is undefined behavior in your code, it doesn't matter what other behavior you observe because it might very well be caused by the undefined behavior problem.
To convert a single char to int you just need to subtract the ascii value of 0 from the ascii value of the digit like this
int n = c - '0';
but that doesn't guarantee that n is the value you expect, for that you need to check with isdigit(c) before attempting to use c as if it were a digit.
Also: The type of c is wrong, it should be int since getchar() returns int and you don't want the value to be truncated.

How are these characters produced?

int main(void)
{
char s[] = "Hsjodi", *p;
for(p = s; *p; p++)
--*p;
puts(s);
return 0;
}
The output writes Grinch but I cant understand how this code executes. How can it write out Grinch when such letters G,r,i for example does not exist in the char array and when does loop terminates our exactly does *p means?
First of all, notice that for loop does not have any braces to create a block, so the loop body is only
--*p;
which is same as
--(*p);
Now, as per the above statement all the elements in the array, until the terminating null, has been reduced one place. That means, H is now G, s is now r and so on.NOTE
Also, the condition check in the loop *p is a short-hand form of writing *p != '\0' or *p != 0.
After the decrement through the loop, the modified array has been printed through puts().
NOTE: You may want to check the ASCII table for reference.

while(*p++) loop doesn't print the first element of the string

I have a stored a string in a pointer variable which has memory in heap section. When I print the string character by character the first element is skipped.
Example: if char *p="hello" when i print character by character using while(*p++) loop 'h' is skipped and output is "ello" please can any one explain it?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *p=(char*)malloc(sizeof(char)*20);
printf("enter string\n");
scanf("%s",p);
while(*p++)// value is assign and address is increased
{
printf("%c",*p);//why first character is skipped??
}
return 0;
}
To see the first letter, change *p to p[-1], because p++ has already incremented p, so by the time you first use *p, p already points to the 2nd letter (with index 1).
There are many other ways to solve it, e.g.
for (; *p; ++p) {
putchar(*p);
}
Because while(*p++) increments the value as soon as the loop starts. By the time the printf statement is reached, p has already been incremented.
p = 0
while(p++) { // p = p + 1
printf('%d', p); // p = 1 when this executes
}
while(*p++) after this statement p is incremented and moved ahead. So at printf() p already points to 2nd character.
The line while(*p++) will check the value of *p and then increment p, before entering the body of the loop. You can improve the code by using a for loop
for ( ; *p; p++ )
printf( "%c", *p );
or by incrementing the pointer after using it, in the body of the loop
while(*p)
printf( "%c", *p++ );

Can someone explain this C code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Can someone explain this reverse sentence code for me? How does the first and the second looping works? What's the point of each of them?
main(){
char arr[255], *p;
printf("Enter string: ");
gets(arr);
for(p=arr; *p!='\0'; p++);
for(p--; p>=arr; p--){
printf("%c",*p);
}
}
Input:
I love you
Output:
uoy evol I
The code is basically printing in reverse the input array.
for(p=arr; *p!='\0'; p++);
Sets p as the last (relevant) element of the array (the null character)
for(p--; p>=arr; p--){
printf("%c",*p);
}
starts from the last (none null) character and prints each one from last to first.
Question for you:
What happens if the input array is longet than 255 chars? (answer below)
buffer overflow
Suppose the input is Hello World. This gets stored in your buffer arr as
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
Your pointer is set to arr, hence the pointer points to H
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
^
|
p
The first loop advances (p++) until it meets the first null character (\0). It now looks like
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
^
|
p
Now the second loop goes back (p--) until it reaches the first character again (actually, until the pointer equals the pointer to the beginning of the array), printing each character as it meets it. The first character \0 however is ignored with the little p-- here:
for(p--; p>=arr; p--)
^^^
The code looks clever, but it actually exhibits undefined behavior, which means the code may do anything.
The problem is the second loop:
for(p--; p>=arr; p--){
printf("%c",*p);
}
What it's intended to do is to start p at the last character of the string (excluding the terminating \0, then keep decrementing it until all the characters of the string have been output in reverse order.
The problem is the termination condition: after the intended end of the loop, p is arr, and then p-- subtracts one, and then p >= arr is false.
Unfortunately, an arithmetic operation on pointers may not result in a pointer that no longer points to the object (or one after the final object of an array), or it's undefined behavior.
That's what's happening here: p-- causes p to be off the array, and all bets are off as to what happens next.
Here's a correct way to write the second loop:
for (int i = (p-arr)-1; i >= 0; i--) {
printf("%c", p[i]);
}
I'd probably write the entire code using indexes to completely avoid pointer arithmetic. Maybe something like this:
int i = 0;
// Find the terminating \0 byte
while(p[i])i++;
// Iterate backwards through the string, outputting characters along the way.
while(--i >= 0)putc(p[i]);
Before explaining the code, I must say two things - first, the signature of the main function should be one of the following -
int main(void);
int main(int argc, char *argv[]);
and second, do not use gets. It's not safe to use. Use fgets instead. Now, coming to the code.
for(p = arr; *p != '\0'; p++) ;
In the above loop, p is assigned the base address of the array arr, i.e., the address of the first element of the array arr. The array arr contains a terminating null byte which means it is a string. The loop body is the null statement ; which means p is incremented till the null byte is encountered, i.e., when the test *p != '\0' fails. In the for loop
for(p--; p >= arr; p--) {
printf("%c",*p);
}
p is first decremented to point to the last character just before the null byte and then it is printed in each iteration till the condition p >= arr is true, i.e., till the first element of the array is reached. You should change your code to -
#include <stdio.h>
int main(void) {
char arr[255], *p;
printf("Enter string:\n");
fgets(arr, sizeof arr, stdin);
for(p = arr; *p! = '\0'; p++)
; // the null statement
for(p--; p >= arr; p--)
printf("%c", *p);
return 0;
}

C, pointer, string

main()
{
char *x="girl";
int n,i;
n=strlen(x);
*x=x[n];
for(i=0;i<n;i++)
{
printf("%s \n",x);
x++;
}
}
What is the output?
Please explain the output.......................
o/p is :
irl
rl
l
The output is undefined behaviour. You modified a string literal.
As others have pointed out, the program as written has undefined behaviour.
If you make a small alteration:
char x[] = "girl";
then I believe it is legal, and possible to explain. (EDIT: Actually there are still problems with it. It's int main(), and you should return 0; at the end. You also need to #include <string.h> because you are using strlen, and #include <stdio.h> because you are using printf.)
The line
*x = x[n];
sets x[0] (i.e. *x) to x[4] (which happens to be the string terminator '\0'). Thus the first string to be printed is the empty string, because the very first character is the string terminator.
We then loop through the string, one character at a time, printing the substrings:
irl
rl
l
While the result is undefined behavior, as DeadMG said, let's assume you declared x as char x[] = "girl".
You assign 4 to n (since the length of the word "girl" is 4), and you assign the value in x[4] to *x (which is x[0]), but this value is '\0' (null terminator)
Now you loop and print the word from x to the next null terminator, but the first time, the first char is the null terminator, so you get nothing. after that you print the word from incrementing index.
g i r l \0
*x = x[4]:
\0 i r l \0
^ ^ ^ ^
it1 it2 it3 it4 // << Where does x points to in each iteration of the for loop
The code is distictly suspect. *x=x[n] attempts to overwrite the literal "girl", and the effect will vary between platforms and compilers. More correctly it should be declared as:
const char *x = "girl";
and then it will not (should not) compile.

Resources