Archived

This topic is now archived and is closed to further replies.

Help on pointers in general.

This topic is 5384 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

I just want to make sure that I finally have a relative grasp on pointers.
  
// 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?


  

Share this post


Link to post
Share on other sites
- 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).

Share this post


Link to post
Share on other sites
SO... this is what it SHOULD be

    
// 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


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?



[edited by - zackriggle on March 23, 2003 3:05:21 PM]

Share this post


Link to post
Share on other sites