Thread: String Copying Probleming

  1. #1
    Registered User
    Join Date
    Oct 2002

    String Copying Probleming


    i'm trying to copy a const char* string (call it stringA) to a char* string (stringB).

    now lets say stringA is 20 characters long and i only want to copy 10 of those characters to stringB. Whats the best possible way to go about doing it?

    i've tried using a for loop..

    int i;
    for (i=0; i < 10; i++)
         stringB[i] = stringA[i];
    stringB[i] = '\0';
    ... but this only results in a segmentation core fault.

    then i tried using strncpy...

    strncpy(stringB, stringA, 10);
    .. but this isnt giving me the results i want. its copying the whole stringA into stringB.

    what am i doing wrong? Any help would be great.


  2. #2
    S Sang-drax's Avatar
    Join Date
    May 2002
    Göteborg, Sweden
    Could you post a complete program that isn't working? Your examples looks correct.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  3. #3
    Registered User
    Join Date
    Oct 2001
    If stringB is declared like this:
    char* stringB;
    then you need to allocate memory with new.

    Or declare it with at least 11 characters like this:
    char stringB[11];

  4. #4
    Registered User major_small's Avatar
    Join Date
    May 2003
    since it looks like you're using C-style strings, don't forget to add the '\0' at the end of the loop... most likely you're trying to write to space you never allocated...

    this code compiles fine:

    int main()
    	int i;
    	const char*stringA="This String is more than 10 characters long";
    	char*stringB=new char[11];
    	return 0;
    don't forget to delete stringB when you're done with it too...
    Last edited by major_small; 04-08-2004 at 11:04 AM.
    Join is in our Unofficial Cprog IRC channel
    Channel: #Tech

    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM