PDA

View Full Version : pointers when passed as parameters



Skarr
01-04-2003, 10:06 AM
I've been wondering: what happens to a pointer when it's passed as a parameter to a function? Why is this:

<code>

int main(void) {

char *str;
*str = 'a';

return 0;

</code>

not legal, while this is perfectly legal:

<code>

void function(char *);

void function(char *str) {

*str = 'a';

}

int main(void) {

char *str;

function(str);

return 0;

}

</code>

Thanks
Skarr

Skarr
01-08-2003, 01:10 PM
I know that, but if I initialize the string in main() I would have a locked size for my string. And if i read stuff from (say) a file, I won't know how big tje buffer should be.

IfYouSaySo
01-08-2003, 04:14 PM
I don't think it's a good idea either way. Your char* points to garbage, so you need to point it to an actual buffer:



void funct(char* buffer, int size)
{
/* do whatever operation you want on up to size
bytes of the buffer */
}

int main()
{
/* obviously you must define MAX_BUFFER_SIZE to
something approprate somewhere */
char buffer[MAX_BUFFER_SIZE];
char* pbuffer = buffer;

/* of course you could just pass buffer too */
funct(pbuffer, MAX_BUFFER_SIZE);

return 0;
}