Hi, i had this exercise in the book I'm reading and I'm wondering if i did it right like the author would want it would be done
3. Write a function void to_lower(char* s), that replaces
all uppercase characters int the C - style string s with
their lowercase equivalents. For example "Hello, World! becomes hello, world!"
Do not use any standard library functions
A C - style string is a zero terminated array of characters, so if you
find a char with the value 0 you are at the end
I don't quite understand 1 thing that's why i'm asking.
Normally i would create simple pointer to int variable like this
1 2
int x = 2;
int* p = &x;
Than i would give this p or &x as argument to the function that expects int* as argument
Here function expects char* but instead received char
I cant create pointer to array without specifying number of elements it holds;
1 2 3
char string[] = "Hello, World!0";
char* p = &string; // not working
char* p = &string[14]; // this is working
If i didn't give my to_lower(char* s) pointer p (char* p = &string[14]) as argument or reference &string[14] as argument, how can this be actually working (which it does)?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
void to_lower(char* s){
for (int i = 0; s[i] != '0'; i++){
if (s[i] >= 65 && s[i] <= 90) s[i] += 32;
}
}
int main(){
//C - style string is a zero terminated array of characters
char string[] = "Hello, World!0";
to_lower(string);
cout << string << endl;
system("pause");
}
Here you're creating an array - char string[] = "Hello, World!0";
Here you are passing the array - to_lower(string);
And here your function is receiving it - void to_lower(char* s)
Thats how it works. When you pass an array to a function, that function must have a pointer as a parameter. This will also work -
void to_lower(char s[]) // []
Those are the two ways to pass on an array.
Edit: Also Im not 100% sure, but I think creating an array with empty brackets like in your program, is c++, not C.
char foo[] = "Hello, World!0";
char* p = &foo; // not working
char* p = &foo[14]; // not what you think XX
char* p = foo; // the correct one
char* p = &foo[0]; // ok too
Arrays decay to pointers in several circumstances.
XX you do dereference the array to reach one character and then take the address of that character. That is not the address of the first character.
You have misunderstood the "zero terminated". You write a literal character 0 and compare against literal 0. How would you to_lower "I have 10 Dollars"?
Zero termination means using numeric 0. Your to_lower assumes that 'A' has numeric value 65. The literal '0' has some numeric value too, but it is not 0.
The literal representation of numeric 0 is '\0'. A literal string that is created with doublequotes does contain terminating zero. These two are equivalent:
1 2
char foo[] = "Hello0"; // foo has 7 elements
char bar[] = { 'H', 'e', 'l', 'l', 'o', '0', '\0' }; // bar has 7 elements