Jump to content
  • Advertisement
Sign in to follow this  
rholding2001

Passing a char array to a char array

This topic is 4945 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
I've quickly wrote this little example:


#define BUFFERLEN 256

class 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!

Share this post


Link to post
Share on other sites
Hi rholding.

Here's a working example. Feel free to ask about it.


#include <string.h>
#include <iostream>

using namespace std;

#define BUF_SIZE 1000

class 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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!