Thread: copying char pointers

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    58

    copying char pointers

    hi,i got a string,whose data is 'one two'. i wanted to manually copy the 'one' into another string.i was using char pointers. but somehow, the copying of the char data doesn't work.
    I wanted the string b to have the data of 'one'. was using microsoft visual c++2003 compiler.

    My code is below,if someone could rectify the error,its much appreciated.thanx..
    Code:
    	
    	char *a="one two";
    	char *b;
    
    	
    	while(*a!=' '){
    		cout<<*a; a++; 
    		
    		*b=*a;  //error line
    	}
    	cout<<b;

  2. #2
    Registered User
    Join Date
    Apr 2007
    Location
    Sweden
    Posts
    41
    Unless you reserve memory for the new string, that's what you get. But you shouldn't do this at all, you should use std::string. One of the beauties of C++ vs C, is that in C++ you can keep pointer fiddling to an absolute minimum (and for your own sake, you should), whereas it was something inevitable in C.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    What you should do is probably read a good lesson on pointers and arrays, and their relationship with each other.

    The idea behind a C-style string is that it is a sequence of characters that end with a '\0' char. In C, you do this with an array, where each element of the array holds one character, including the ending '\0' char. Where pointers come in is that arrays are often referred to simply by a pointer to the first element in the array. Since arrays are stored sequentially in memory, you can easily find each character of the string by simply walking through the memory until you reach the terminating '\0' char.

    What you have in your code section is, first of all, a pointer named a that points to a block of memory. You then have a pointer named b that points to some random place because you didn't initialize it to point anywhere. It doesn't point to the first element of any valid array at this point. Therefore, you can't copy stuff to it. You're doing it anyway in the loop, and this will result in undefined behavior (most likely your program crashing in this case).

    What you should do is something similar to this:

    Code:
    #include <iostream>
    #include <cstdlib>
    
    int main(int argc, char *argv[])
    {
    	int i;
    	char *a = "String 1";
    	char *b = (char *)malloc(strlen(a)+1); /* Note, casting is needed because this is C++. */ 
    	
    	for(i=0;a[i] != '\0';i++)
    	{
    		b[i] = a[i];
    	}
    	b[i] = '\0';
    	
    	std::cout << "a: " << a << std::endl;
    	std::cout << "b: " << b << std::endl;
    	
    	free(b);
    	
    	return 0;
    }
    There are much better ways of writing this, however, this should be straightforward enough to understand the concept behind it.

    Now with that said......

    You should be using C++ strings instead of C-style strings when you can. C++ strings are much safer and easier to deal with.

    Code:
    #include <iostream>
    
    int main(int argc, char *argv[])
    {
    	std::string a("String 1");
    	
    	std::string *b;
    	b = new std::string(a);
    	
    	std::cout << a << std::endl;
    	std::cout << *b << std::endl;
    	
    	delete b;
    	
    	return 0;
    }
    Last edited by MacGyver; 05-06-2007 at 03:03 AM.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    new[] and delete[] could be used for the first version, no need for malloc():

    Code:
      char *b = new char[strlen(a)+1];
      // stuff
      delete[] b;

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > /* Note, casting is needed because this is C++. */
    So use
    char *b = new char[ strlen(a)+1 ];
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    You guys are correct that new and delete should be used, but since he's going all retro with char pointers, I figure malloc() and free() are not totally inappropriate for the example.

    Apologies if my assumption is incorrect.

  7. #7
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    Almost identical question:

    http://cboard.cprogramming.com/showthread.php?t=89547

    Please take note of CornedBee's solution in that thread using a nice, safe std::vector stl container to sidestep dynamic memory allocation/deallocation shenanigans.
    CProgramming FAQ
    Caution: this person may be a carrier of the misinformation virus.

  8. #8
    The larch
    Join Date
    May 2006
    Posts
    3,573
    There is no reason to allocate a string object dynamically here
    Code:
    	/*std::string *b;
    	b = new std::string(a);*/
            std::string b(a);
    There is also no reason to write new "retro code" in C++...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  9. #9
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    *sigh*

    The OP was asking how to do something you don't need to do in C++ most of the time, if at all. I showed him how to do it, but I said it was incorrect because C++ has, among other things, the string class.

    The reason I used a string pointer in the second example was because the OP was using char pointers, and I wanted to show the contrast between dynamically allocating a block of memory for a char * and then dynamically allocating a string object.
    Last edited by MacGyver; 05-06-2007 at 01:12 PM. Reason: Bleh.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. copying pointers
    By Tom Bombadil in forum C Programming
    Replies: 10
    Last Post: 05-22-2009, 01:26 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  4. String sorthing, file opening and saving.
    By j0hnb in forum C Programming
    Replies: 9
    Last Post: 01-23-2003, 01:18 AM
  5. errors in class(urgent )
    By ayesha in forum C++ Programming
    Replies: 1
    Last Post: 11-10-2001, 10:14 PM