Passing a char array to a char array
hi there. I did a post the other day about finding a char in a string and the response was more than i ever hoped for. I however have another problem..
heres the situation
1. 1 class (classA) recieves a message from a server and saves it as buffer. this message is then sent to another class (classB). classB takes a pointer to the buffer and couts it to the screen from the classB. I want to put this into a char array. I keep getting errors like cannont comvert char to char[50] or char* to char. How do i get this buffer into an array.
i need it in a array that has no specified size to if the string is 5 chars it would read "12345\0"
thanks for any help people
I've quickly wrote this little example:
That should do it ... to copy the string to the buffer you have to call strcpy (or in this case strncpy to avoid buffer overflows if the message is longer). From your post I don't know where exactly your problem lies ...
Hope that helps!
#define BUFFERLEN 256class B{ ... void PrintMessage(char *msg) { cout << msg; }}class A{ char buffer[BUFFERLEN]; B* b; ... void ReceiveMessage(char *msg) { strncpy(buffer, msg, BUFFERLEN - 1); b->PrintMessage(buffer); }};
That should do it ... to copy the string to the buffer you have to call strcpy (or in this case strncpy to avoid buffer overflows if the message is longer). From your post I don't know where exactly your problem lies ...
Hope that helps!
Hi rholding.
Here's a working example. Feel free to ask about it.
Greetings and a happy new year,
Bas
Here's a working example. Feel free to ask about it.
#include <string.h>#include <iostream>using namespace std;#define BUF_SIZE 1000class classB {public:char * buf; //set buf array void setBuffer(char * buffer) { int size = strlen(buffer); buf = (char *) malloc(size + 1); memcpy (buf, buffer, size + 1); } //print it on the screen void printBuf() { cout << buf; } //a pointer can be referenced like an array, example: //char c = buf[0] //c will be 'h'};//the function within class A (now called main to make it work):int main() { //Buffer received from server char * buffer = (char *) malloc (sizeof(char) * BUF_SIZE); memcpy (buffer, "hello world", 12); //fill the buffer with an example string classB b; b.setBuffer(buffer); b.printBuf(); return 0;}
Greetings and a happy new year,
Bas
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement