"mm" is local to the function only, and when the function exits, it becomes 'invalid' (that is, it may still contain what you put there for some time, but at any moment, the OS may reclaim that chunk and use it for something else).
The second problem is that get() creates a COPY of the pointer you passed it, so to manipulate the actual pointer, you have to pass it's address. Let's look at the second issue first:
Code:
void advance(char * p)
{
p++;
}
int main()
{
char buffer[100] = "Hello.";
char * p = buffer;
advance(p);
printf(p);
}
Notice that it prints ""Hello.", not "ello." So to accomplish this you have to pass it's address:
Code:
void advance(char ** p)
{
*p++;
}
int main()
{
char buffer[100] = "Hello.";
char * p = buffer;
advance(&p);
printf(p);
}
This would indeed print "ello.".
So back to the first problem, you CANNOT create a variable within a function, and return it's address, period. Your only options are then to:
1) pass the variable INTO the function.
2) return a dynamically allocated variable.
3) return a static variable.
4) return a global variable.
1)
Code:
void get(char ** p, char * buffer)
{
*p = buffer;
}
2)
Code:
void get(char ** p)
{
*p = malloc(100);
}
3)
Code:
void get(char ** p)
{
static char buffer[100];
*p = buffer;
}
4)
Code:
char buffer[100];
void get(char ** p)
{
*p = buffer;
}
Of these, 3 and 4 are REAL bad practices, 2 can cause memory leaks, and 1 is best.
But in reality, this sort of function just isn't used. If you need a pointer to something, instead of passing the address of a pointer, just return one:
Code:
char * get(char * buffer)
{
char * p = buffer;
return p;
}
Notice that although we created 'p' within the function, we didn't return it's address (which would violate good sense). We simply returned THE VALUE of the address that it points to.
So lets create a real function, and set it up both ways:
Code:
void find(char * buffer, char letter, char ** found)
{
*found = 0; // signifies 'not found'
int i;
for(i = 0; buffer[i] != 0; ++i)
{
if(buffer[i] == letter)
{
*found = &buffer[i];
break;
}
}
}
int main()
{
char buffer[100] = "Hello";
char * found;
find(buffer, 'e', &found);
if(found != 0)
printf("Found it.");
else
printf("Not found");
}
Next, we will use the more accepted style:
Code:
char * find(char * buffer, char letter)
{
char * found;
found = 0; // signifies 'not found'
int i;
for(i = 0; buffer[i] != 0; ++i)
{
if(buffer[i] == letter)
{
found = &buffer[i];
break;
}
}
return found;
}
int main()
{
char buffer[100] = "Hello";
char * found;
found = find(buffer, 'e');
if(found != 0)
printf("Found it.");
else
printf("Not found");
}
Did that help any?