PDA

View Full Version : pointers



SPEKTRUM
01-26-2002, 09:00 PM
How would I allocate a string? example:

char * myvar;
char * myvar2;

myvar=myvar2;

I need to allocate myvar so that if I change myvar2, myvar won't change, even though its pointing to it.

Thanks for anyhelp.

mix0matt
01-27-2002, 12:24 AM
you question doesn't make much sense....really...

the statement: myvar = myvar2 assigns the value in myvar2, which is an address of a memory location to the pointer variable myvar. this causes both pointer to point to the same address. myvar2 does not point to myvar.

char** myvar2 = &myvar; //now myvar2 points to myvar.

i really can't understand what your trying to do. i need more explination.

ozgulker
01-27-2002, 03:34 AM
use strcpy to allocate a string from another;

char *str1 = "something";
char *str2;

int size = strlen(str1) + 1;
str2 = (char*) malloc(size);
strcpy(str2, str1);

By the way, do you want to mean that changing myvar is changing the content of the string or the pointer?

Strut
01-27-2002, 11:55 AM
Yes, it causes them to point to the same adress. myvar will always equal myvar2. If myvar2 changes, then myvar will change to whatever myvar2 is changed to. I needed to correct this, whilst using a pointer for the char. mix0matt i think gave me a possibly explination on how to cprrect this.


thank you both for your help. (btw, name changed to Strut)