// I just want someone to tell me if all of this will work...
char * ptr;
char str1[] = "This is string number 1!";
char str2[] = "This is string number 2!";
ptr = str; // Sets ptr to point to str, so that if I passed
// it into a function it would be the same as passing
// the actual string assigned to str1. Correct?
// Make ptr point to a new character array
delete ptr; // Is this necessary?
ptr = new char[strlen(str2)+1]; // I think we need a +1 to have
// room for the terminator
// Copy str2 to the character array pointed at...
strcpy(ptr,str2); // This puts the string into the char array
// pointed to by ptr, correct?
strcpy(str1,ptr); // This is the same thing as:
// strcpy(str1,str2); correct?
delete[] ptr; // This is necessary to prevent memory links, right?
ptr = NULL;
char *ptr2 = NULL;
ptr2 = str2;
ptr = *ptr2; // The same as saying ptr = str2, right?
Help on pointers in general.
I just want to make sure that I finally have a relative grasp on pointers.
- You should never use delete on memory that you have not allocated with new.
- ptr = *ptr2 should not compile. ptr is of type char*, so when you dereference it you are referring to something of type char: Specifically, the particular character to which the pointer is pointing (the first character of the string).
- ptr = *ptr2 should not compile. ptr is of type char*, so when you dereference it you are referring to something of type char: Specifically, the particular character to which the pointer is pointing (the first character of the string).
For the love of God, don't try to delete a static array. BSoD ahoy!
[edited by - micepick on March 23, 2003 2:40:28 PM]
[edited by - micepick on March 23, 2003 2:40:28 PM]
SO... this is what it SHOULD be
[edited by - zackriggle on March 23, 2003 3:05:21 PM]
// I just want someone to tell me if all of this will work...char * ptr;char str1[] = "This is string number 1!";char str2[] = "This is string number 2!";ptr = str;// Sets ptr to point to str, so that if I passed // it into a function it would be the same as passing // the actual string assigned to str1. Correct? // Make ptr point to a new character arrayptr = new char[strlen(str2)+1]; // I think we need a +1 to have // room for the terminator // Copy str2 to the character array pointed at...strcpy(ptr,str2); // This puts the string into the char array // pointed to by ptr, correct?strcpy(str1,ptr); // This is the same thing as: // strcpy(str1,str2); correct?delete[] ptr; // This is necessary to prevent memory links, right?ptr = NULL;char *ptr2 = NULL;ptr2 = str2;ptr = ptr2; // The same as saying ptr = str2, right?
[edited by - zackriggle on March 23, 2003 3:05:21 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement