Can someone explain this C code? [closed] - c

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

Related

Problem while printing string using Pointers in C Programming

Respected Experts ,
I am a newbie to C programming Language .
I am trying to print a string in C Language . The code runs successfully but when i
enter the string , it does not displays the string entered by the user in return
I have attached the screenshot of the code which I am trying to execute .
Please help me out .
#include<stdio.h>
int main()
{
char str[20];
char *pt;
printf("Enter any string :\n");
gets(str);
pt=&str[0];
for(*pt=0; *pt != '\0'; *pt++)
{
printf("%c", *pt);
}
}
The initialization *pt = 0; is causing the continuation test *pt != 0 to fail immediately, so your loop stops before printing anything.
You already initialized pt before the loop, so you don't need that step in the for() header. And you should be incrementing the pointer, not the character that it points so, so the update should be pt++.
for (; *pt != '\0'; pt++) {
printf("%c", *pt);
}
BTW, ptr = &str[0]; can be simplified to just ptr = str;. It's also more idiomatic to put this in the for header, so it would be:
for (pt = str; *pt != '\0'; pt++)
First - NEVER NEVER NEVER use gets, not even in toy code. It was deprecated in the 1999 standard and has been removed from the standard library as of the 2011 standard. It will introduce a point of failure / major security hole in your code. Use fgets instead, just be aware it will store the newline to your buffer if there's room.
Restructure your for statement as follows:
for ( pt = str; *pt != '\0'; pt++ )
The first expression sets pt to point to the first character in str (in this context, str is equivalent to &str[0]). The second compares the value of the element that pt points to against the string terminator. Since you are trying to check the value of the pointed-to object, you must use the * operator to deference pt. The final expression advances pt to point to the next character in the string.
Finally, is there a reason you're printing the string out character by character instead of just writing printf( "%s\n", str ); ?

How does a char pointer differ from an int pointer in the below code?

1)
int main()
{
int *j,i=0;
int A[5]={0,1,2,3,4};
int B[3]={6,7,8};
int *s1=A,*s2=B;
while(*s1++ = *s2++)
{
for(i=0; i<5; i++)
printf("%d ", A[i]);
}
}
2)
int main()
{
char str1[] = "India";
char str2[] = "BIX";
char *s1 = str1, *s2=str2;
while(*s1++ = *s2++)
printf("%s ", str1);
}
The second code works fine whereas the first code results in some error(maybe segmentation fault). But how is the pointer variable s2 in program 2 working fine (i.e till the end of the string) but not in program 1, where its running infinitely....
Also, in the second program, won't the s2 variable get incremented beyond the length of the array?
The thing with strings in C is that they have a special character that marks the end of the string. It's the '\0' character. This special character has the value zero.
In the second program the arrays you have include the terminator character, and since it is zero it is treated as "false" when used in a boolean expression (like the condition in your while loop). That means your loop in the second program will copy characters up to and including the terminator character, but since that is "false" the loop will then end.
In the first program there is no such terminator, and the loop will continue and go out of bounds until it just randomly happen to find a zero in the memory you're copying from. This leads to undefined behavior which is a common cause of crashes.
So the difference isn't in how pointers are handled, but in the data. If you add a zero at the end of the source array in the first program (B) then it will also work well.
In str2, You have assigned String. Which means there will be end Of
String('\0' or NULL) due to which when you will increment Str2 and it will
reach to end of string, It will return null and hence your loop will break.
And with integer pointer, there is no end of string. thats why its going to infinite loop.
Joachim gave a good explanation about String terminal character \0 in C language.
Another thing to be aware of when working with pointer is pointer arithmetic.
Arithmetic unit for pointer is the size of the entity pointed.
With a char * pointer named charPtr, on system where char are stored on 1 byte, doing charPtr++ will increase the value in charPtr by *1 (1 byte) to make it ready to point to the next char in memory.
With a int * pointer named intPtr, on system where int are stored on 4 bytes, doing intPtr++ will increase the value in intPtr by 4 (4 bytes) to make it ready to point to the next int in memory.

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++ );

Unexpected C code output

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.

Resources