Reputation: 65
I want to create a char array, let's call it a buffer. Then I want to pass a pointer to the buffer to various functions and manipulate the buffer.
Here is a snippet that describes the goal:
void manipCharBuffer(char* buffer) {
buffer = "DERP";
cout << buffer;
}
int main() {
char buffer[256] = "JUNK STRING";
std::cout << buffer;
manipCharBuffer(buffer);
ctd::cout << buffer;
}
Why doesn't manipCharBuffer
alter the buffer? It's like it still only has local scope inside the function.
Upvotes: 0
Views: 1678
Reputation: 281
It is not possible to pass C arrays by value, however it is possible for C++ arrays (std::array) and dynamic arrays (std::vector).if you want to use c++ ,its better to use standard library.
#include <iostream>
#include <string.h>
using namespace std ;
void manipCharBuffer(char* buffer) {
strcpy(buffer,"DERP");
cout << "\n string in called function "<<buffer;
}
int main() {
char buffer[256] = "JUNK STRING";
cout << " string before call is : " <<buffer;
char*p = buffer ;
manipCharBuffer(p);
cout << "\n string after call is : " <<buffer;
return 0;
}
Upvotes: 0
Reputation: 363
In your main function the variable buffer points to an array of 256 characters allocated on the stack. When sending it to the function manipCharBuffer, the address is transfered by value. That means each call for the function manipCharBuffer creates a local variable also named buffer, which is stored in a different place in memory from the variable buffer in the main function but both point to the same place in memory. So the result of the line:
buffer = "DERP";
is that the local variable in the function now points to a different place in memory where the string-constant "DERP" is stored (determined in compile time) without changing that buffer you allocated on the stack, and the buffer variable in main still points to it.
What you tried to do can be achieved as follows:
memcpy(buffer,"DERP",sizeof(char)*5); //5 and not 4 to include the null terminator
Upvotes: 0
Reputation: 141586
Inside this function:
void manipCharBuffer(char* buffer) {
buffer = "DERP";
the name buffer
is a different name to buffer
in main
. To avoid confusion you could use a different variable name, e.g.:
void manipCharBuffer(char* p_buffer) {
p_buffer = "DERP";
Hopefully this makes it clearly why there is no difference made to main
here. You are setting the local pointer p_buffer
to point to a different char array. ("DERP"
is a char array located somewhere in memory).
If you want to copy characters from one char array to another the you have to write code that copies characters; one way would be:
std::strcpy( p_buffer, "DERP" );
Upvotes: 2
Reputation: 2278
Here's a real world analogy of what's happening. I write down my phone number on a sheet of paper. I give you a copy of that sheet of paper. On the copy, you erase my number and write your own. Then you call the number that you just wrote.
Upvotes: 2