Hello, my name is Estella. I have a question about using strtok() to store strings in global variables... because I got quite stuck in my functions...
I declared global variables:
Code:
// Global variable
char *namePtr[100] = {0};
int n; /*number of components*/
I wrote a function eat_path to split a string into components:
e.g. /a/b/c => namePtr[0] = a, namePtr[1] = b, namePtr[2] = c
In eat_part function:
Code:
void eat_path(char *pathname)
{
printf("Enter eat_path\n");
//eat_path() breaks up a pathname into component strings.
//Example : pathname = /this/is/a/test
//Then n=4, namePtr[0] ="this", namePtr[1] ="is", namePtr[2] ="a",
//namePtr[3] ="test"
//The component names will be used to search for a child under its
parent
char path[40];
char delim[] = "/"; /* delimiter is '/' */
int i = 0, j = 0;
strcpy(path, pathname);
namePtr[j++] = strtok( path, delim );
while(namePtr[j++] = strtok( NULL,delim ));
j--;
n = j;
printf("\nNumber of components: %d\n", n);
for(i = 0; i < n; i++)
{
printf("%d %s\n", i, namePtr[i]);
}
printf("eat_path ends\n");
}
It works fine when I printed the namePtr inside this function, but
when I print namePtr in another function. it prints out garbage...
This is another function that calls eat_path:
Code:
NODE *namei(char *pathname)
{
NODE *ret;
int i = 0;
//namei() returns the node pointer of a pathname, or 0;
//First, call eat_path() to break up pathname into component strings.
printf("In namei(), pathname = %s\n", pathname);
eat_path(pathname);
printf("After eat_path: In namei(), pathname = %s\n", pathname);
for(int j = 0; j < n; j++)
printf("%d %s\n", j, namePtr[j]);
//For each component string, call search_child() to look for the
child
//under its parent.
if (pathname[0] == '/')
ret = root;
else
ret = cwd;
while (ret != 0 && i < n)
{
//printf("namePtr[%d] = %s\n", i, namePtr[i]);
ret = search_child(ret, namePtr[i]);
i++;
}
return ret;
}
I checked the content of namePtr right after calling eat_path, so the
namePtr should contain the same thing when the program is still inside
eat_path...
I am so lost... thank you for helping..