Click here to Skip to main content
15,913,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Here the str array used in the main function and str used in input function are not same variables. They have different scopes and life times.
Then by using printf() function, why I am able to print the str array?
Here , There is no return type of the string from the function input.
There is only return type of number of characters which is stored in variable n.
Why I am able to print the str array, whose scope and life time are already over?


Here
the input : abcdefghijklmnopqrstuvwxyz
the output : 5abcde

What I have tried:

C++
#include<stdio.h>
int input(char str[],int n)
{
    int ch,i=0;
    while((ch=getchar())!='\n')
    if(i<n)
    str[i++]=ch;
    str[i]='\0';
    return i;
}
int main()
{
    char str[100];
    int n=input(str, 5);
    printf("%d %s",n,str);
    return 0;
}
Posted
Updated 25-Apr-21 20:06pm
v2
Comments
OriginalGriff 25-Apr-21 12:19pm    
Come on - you've posted enough code snippets here to know what happens if you don't use a code block and your code contains a "less than" character!
The rest of the code is swallowed by the browser and no-one can see it ...

Edit your question (using the "Improve question" widget - just hover the mouse over the question) and repaste the code, using the "code" widget to apply "C++" formatting.
(C is an old, old language, and isn't supported directly by the formatter. Since C++ is a superset of C the C++ formatter works perfectly).
Patrice T 25-Apr-21 13:31pm    
Reread the question, code is missing.
Use Improve question to update your question.

1 solution

In your input function the address of the str array, defined in main, is passed (by value), hence the function itself is able to modify the array content. On the other hand, it cannot modify the array address.
 
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