Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
juzz little bit confusion one query
#include<stdio.h>
int main(){
int i;
char s1[]="Hello";
char s2[]="jelly";
char *s3;
s3=s1;
for(i=0; *s3; i++) 
{
printf("%c",*s3);
s3++; //here if i am taking s3+1 why its output is infinite
  }
}


What I have tried:

i have tried prefix tried but same output
Posted
Updated 30-Sep-22 8:23am
v2

Ripping out all the irrelevant stuff and indenting your code:
C
#include<stdio.h>
int main()
    {
    char s1[]="Hello";
    char *s3 = s1;
    for(; *s3; ) 
        {
        printf("%c",*s3);
        s3++; 
        }
    }
If you run this, it prints the content of s1: "Hello" which is what you expect.
The only way to get an "infinite" output using S3 + 1 would be if the output was "HHHHHHHHHHHHHHHHHHHH..." and your code looked like this:
C
#include<stdio.h>
int main()
    {
    char s1[]="Hello";
    char *s3 = s1;
    for(; *s3; ) 
        {
        printf("%c",*s3);
        s3 + 1; 
        }
    }
And that would be because s3 + 1 returns a value one greater than s3 started with, but doesn't alter the content of s3 at all - for that you'd need to do this:
C
#include<stdio.h>
int main()
    {
    char s1[]="Hello";
    char *s3 = s1;
    for(; *s3; ) 
        {
        printf("%c",*s3);
        s3 = s3 + 1; 
        }
    }
Personally, I'd rewrite your code like this:
C
#include<stdio.h>
int main()
    {
    char s1[]="Hello";
    for(char *s3 = s1; *s3; s3++) 
        {
        printf("%c",*s3);
        }
    }
 
Share this answer
 
Quote:
Why output coming in infinite

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900