[英]C pointers - pass by value
I want to know why is it that when i call readF() and have it return the buffer pointer and i print the buffer in main() it prints the actual data and not the memory address? 我想知道为什么当我调用readF()并使其返回缓冲区指针并在main()中打印缓冲区时,它打印的是实际数据而不是内存地址? I am returning the address and not the actual data correct? 我返回的地址不是正确的实际数据吗? In my main i have a pointer that points to what gets returned, which is just what the buffer pointer in readF() points to. 在我的主语言中,我有一个指向返回结果的指针,这就是readF()中的缓冲区指针指向的内容。
char *readF(){
char *buffer=NULL;
//allocate memory to contain the string plus null terminator
buffer=malloc((sizeof(char)*4)+1);
//fill memory with string Hello plus terminator
return buffer;
}
int main(int argc, char **argv){
char *buffer;
buffer=readF();
printf("%s", buffer);
return 0;
}
You print the actual data inside the buffer because you use the %s
format specified in your printf
statement. 您将实际数据打印在缓冲区内,因为您使用了printf
语句中指定的%s
格式。 This tells printf
to assume the pointer it receives, buffer
in this case for the first specifier, is a pointer to a NULL-terminated character string, so it prints the string. 这告诉printf
假定接收到的指针(在这种情况下为第一个说明符buffer
是指向以NULL结尾的字符串的指针,因此它将打印该字符串。
If you want to print the address use the %p
format specifier 如果要打印地址,请使用%p
格式说明符
You're correct when you say the readF
function is returning the memory address. 说readF
函数正在返回内存地址时,您是对的。 It returns the memory address of the first byte of the buffer, ie a pointer to the buffer you allocate. 它返回缓冲区第一个字节的内存地址,即指向您分配的缓冲区的指针。
Note: at the end of your function you should really free(buffer)
too :) 注意:在函数的最后,您也应该真正free(buffer)
:)
To print the address you need %p
specifier. 要打印地址,您需要%p
指定符。
Change 更改
printf("%s", buffer);
to 至
printf("%p", (void *)buffer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.