Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
The following c code has a bug/error in it can you find it?
Ok so I posted this earlier but didn't get any answers but that was probably because it was in the middle of the night and in the wrong category so I'll try again. Here is the code:
include <stdio.h>
#define MAX_LEN 10
char *LowerCase(char *s);
int main()
{
char str[MAX_LEN];
printf("Enter a string : ");
scanf("%s", str);
printf("Lowercase: %s \n", LowerCase(str));
}
char *LowerCase(char *s) {
char newStr[MAX_LEN];
int indeX;
for (indeX =0; indeX < MAX_LEN; indeX++) {
if ('A' <= s[indeX] && s[indeX] <= 'Z')
newStr[indeX] = s[indeX] + ('a' - 'A');
else
newStr[indeX] = s[indeX];
}
return newStr;
}
3 Answers
- Ngo Cong HuanLv 41 decade agoFavorite Answer
There are 3 problems there:
1.If you input a string and its length exceeds MAX_LEN = 10. There will be error there, because the length of and input string is variety. To get the length of any string you can use this function int strlen(char *). Ex to get length of string str you make a call "int length=strlen(str);"
2. Statement "if ('A' <= s[indeX] && s[indeX] <= 'Z')" is not clearly. You should add the brackets to indicate the priority of sub- boolean expression clearly.
3. In function char* LowerCase(char *s) you give back value for function is an local variable that isn't allocation memory for it. And whole content of it will be erased after function done its work.
So all thing is fixed in my function that I rewrite:
char *LowerCase(char *s) {
int length=strlen(s);
char *newStr=new char[length+1]; //Allocate memories for variable
int indeX;
for (indeX =0; indeX < length; indeX++) {
if (('A' <= s[indeX]) && (s[indeX] <= 'Z')) //Add brackets for sub boolean expression
newStr[indeX] = s[indeX] + ('a' - 'A');
else
newStr[indeX] = s[indeX];
}
//Add terminal signal for string
newStr[length]='\0';
return newStr;
}
- Jai Shri KrishnaLv 41 decade ago
there is type mismatch i guess ...the return type of the user defined function is charecter and you have declared int main()?
u are returning a string to the main function but the main function is of type int..i guess..
correct me if I am rong