Advertisement

char to char *

Started by July 19, 2000 03:46 PM
22 comments, last by KalvinB 24 years, 5 months ago
I''m using DirectPlay and I need to beable to construct messages of variable length at run-time using a char * variable. I''m getting all kinds of errors attempting to do this and I havn''t found any examples anywhere. Ben
I''m not sure that I completely understand the question but you should be able to use malloc to allocate character arrays of different sizes.

ex:

char *data;

data = ((char *) malloc (size));

Advertisement
I''m basically trying to create a variable that acts like a file.

Ben
look up:

strdup, strcpy, strcat, strstr, strchr...

Converting a char to a char* is easy...

char MyChar;
char *pMyChar;

pMyChar = (char *) &MyChar

Hope this helps!

----------------------------------------------
That's just my 200 bucks' worth!

..-=gLaDiAtOr=-..
    	char *str, ch;	int j;	for (j=0;j<10;j++)	{		ch=j+48;		strcat(str,(char *)&ch);	}	cout<<str;    


I need this to print out "0123456789" however, the above gives me errors.

Also, how do I empty the pointer. I get a few junk characters when I convert just one character.

Ben
I always store strings using the string class. To use it you must #include

To convert a string to char* you simply do mystring.c_str()

Easy or what?

You really should not use malloc or free. Use proper c++ and enjoy new/delete and the wonderful STL!
Advertisement
KalvinB: your character pointer has no memory allocated to it, try the following:

char *str, ch;
int j;

/* allocate 11 for the last null character */
str = ((char *) malloc (11));

/* this will ensure that you have the null character at the
end of the string */
memset (str, 0, 11);

for (j=0;j<10;j++) {
ch=j+48;

/* strcat appends one string onto another, ch is not a string
it is a character, the line as you have it written will
start with the address of ch and try to read sequential
characters until it hits a NULL (\0) character. This
will cause your program to access invalid memory
strcat(str,(char *)&ch); */

/* use */
str[j] = ch;
}

/* stubborn c programming verison = printf ("%s",str) :-) */
cout<

/* do more stuff with str*/

free (str); /* free the pointer when you''re done */

Forgive me, but I am a stubborn C programmer and I am proud of it!




PS: How do you get those cool looking code boxes?
    you use [ source ]   [ / source ] without the spaces    

Need help? Well, go FAQ yourself. "Just don't look at the hole." -- Unspoken_Magi
    Like this?    


-blide
blide@mail.com
-blideblide@mail.com

This topic is closed to new replies.

Advertisement