I'm attempting to learn C and going through the K&R book. Many examples online seem to use pointers to return a value from a function. I would think then that the same would be used for this K & R function:
/*
Reverse a string in place
*/
void reverse(char s[])
{
int c, i, j;
for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
int main()
{
char s[] = "HELLO";
reverse(s);
printf("%s", s);
return (0);
}
I would think that the string would NOT be reversed in this situation. Yet it prints the char array backwards as originally intended by the author.
How does it do that? I don't completely understand pointers yet but I was thinking it would be like reverse(&s) and then void reverse(char *s[]) {...}
void reverse(char s[]);is 100% absolutely the same asvoid reverse(char *s);s, is achar *, for all that the notationchar s[]was used in the parameter list. It's a straightforward use of array subscripting. As the argument is not a string literal, it should work fine (as long as you don't pass an empty string to the function).int a[] = {1,2}; int c; c=a[0]; a[0] = a[1]; a[1] =c;What happens?