C - Tracing where pointers point to in a program.
2 hours ago, GR412 said:From my understanding a pointer is a variable whose value is a memory address of another variable. And that you declare a pointer like so: int *test; So i know what a pointer is and that it's used for passing by reference, but what confuses me is following where a pointer points to in a program. For example this program:
#include<stdio.h> void up_case(char *c) { if (*c>='a' && *c<='z') *c-=32; } void lo_case(char *c) { if (*c>='A' && *c<='Z') *c+=32; } void traverse(char *s, void (*f) (char *)) { while (*s!='\0') { f(s); s++; } } int main() { char str[]="CTEC2901 Data Structure and Algorithms"; printf("Original: \'%s\'\n",str); traverse(str,up_case); printf("Upper Case: \'%s\'\n",str); traverse(str,lo_case); printf("Lower Case: \'%s\'\n",str); return 0; }I do understand this program, but what i don't get is what char *c in the up_case and lo_case function point to, as well as the char *s, void (*f) and char * in the traverse function. My guess is that char *c in the up_case and lo_case point to the value thats given in. The same with the traverse function char *s points to the char array called str, and the *f points is clearly a function pointer so it would point to either lo-case or up_case.
Like I said i'm not really sure, so if someone could talk me through where each pointer points to in each function I'd be greatful.
In C, a array decays into a pointer, which means that in the lines:
traverse(str,lo_case); //and... traverse(str,up_case);
'str' becomes a 'char *' pointer to the first element in the array, thus it points to the first letter in the string
"CTEC2901 Data Structure and Algorithms". Given this, the traverse function works as follows:
void traverse(char *s, void (*f) (char *)) { while (*s!='\0') //Keep looping as long as the character s is pointing to is not 0 (0 indicates end of string) { f(s); //Call the function pointed to by the function pointer, eighter lo_case or hi_case, and pass the pointer to it... s++; //Increase the pointer by 1, making it point to the next character in the string. } }
So it calls the lo_case or hi_case function for each letter in the string, passing a pointer to the current letter along so the function can work with that letter.

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now