0

This may sound weird but I am my program below is not able to find length of string

#include <iostream>
using namespace std;

int noSize(char * s){
    int i;
    for(i=0;s[i]!='\0';i++){}
    return i;
}
int main() {
     char *name;
     int n;
     cout<<"enter string";
     gets(name);
     n = noSize(name);
    cout<<n;


    return 0;
}

The function I created is not working. But when I copy-pasted the code inside the function and included in the main body, not only did it run but the function also gave the output though I didn't make any changes

#include <iostream>
using namespace std;

int noSize(char * s){
    int i;
    for(i=0;s[i]!='\0';i++){}
    return i;
}
int main() {
     char *name;
     int n,i;


    cout<<"enter string";
     gets(name);
     n = noSize(name);
    for(i=0;name[i]!='\0';i++){}
    cout<<"size of string is "<<i<<endl;
    cout<<"size of string is "<<n;


    return 0;
}

From the earlier code, I didn't get any output but now I am getting 2 outputs,one from for loop in main body and another one from the function. Why so?

MikeCAT
  • 69,090
  • 10
  • 44
  • 65

0 Answers0