What is the difference between a Char* X and a Char *X. In my code for homework we were given a Char* X, and when I tried to access it like a pointed to value (i.e.if *X=='y'), it complained about there being a pointer expected.
What is the difference between a Char* X and a Char *X. In my code for homework we were given a Char* X, and when I tried to access it like a pointed to value (i.e.if *X=='y'), it complained about there being a pointer expected.
There's no difference between "char *x" and "char* x", this is syntactically equivalent for the compiler, the style is up to you.
There must be another difference you didn't spot, post your code.
Code:int CountCharacters(char* String, char Character) { int n=sizeof(*String); int count=0; int i; for (i=0; i<n; i++){ if (*String[i]==Character){ count++; } } return count; }
Your problem is in the following line:
When you use array notation[] on your variable you don't use pointer notation * at the same time. So delete the * and you should be okay.Code:if (*String[i]==Character){
Also your sizeof() call is not giving you the number of characters in your string. Try printing out the value of n after this call. You may want to pass the size of your string into your function.
Jim
Last edited by jimblumberg; 08-20-2012 at 01:59 PM.
Okay.
"String" is a pointer to a character, a string in C is an array of characters, terminated by the character \0.
So if you do "*String", you get the first character of the string.
If you do "String[i]", you get the Ith character of the string.
"*String[i]" makes no sense in your case, that's why the compiler complains, I let you guess how to fix it.
At last the function to get the length of a string is strlen(), not sizeof() and certainly not with *String once again because you're only taking into account a single character.
I suggest you review how strings works in C to be sure everything's clear.
Last edited by root4; 08-20-2012 at 02:02 PM.
Thanks