#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    35
    Rep Power
    12

    How do you copy one char array into another.


    Hi:

    I want to know how to store one char string into another cha string. Is this possible in C?
  2. #2
  3. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    the strncpy() is one of many ways to accomplish this. see here:
    http://www.qnx.com/developer/docs/qn...s/strncpy.html
  4. #3
  5. Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    8
    Rep Power
    0
    You can use following simple function

    void StrCopy(char* str_1, char* str_2)
    {
    while(*str_1 != '\0')
    {
    *str_2 = *str_1++;
    ++str_2;
    }
    }
  6. #4
  7. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    244
    Keep in mind that these string copy routines all require that the final character be a NULL ('\0'). If not, you get memory overwrites which can cause nightmarish debugging.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  8. #5
  9. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,643
    Rep Power
    4247
    Originally posted by Oxo
    You can use following simple function

    void StrCopy(char* str_1, char* str_2)
    {
    while(*str_1 != '\0')
    {
    *str_2 = *str_1++;
    ++str_2;
    }
    }
    Why reinvent the wheel, when there are perfectly good functions to do this in the standard library. See strcpy() and strncpy() from here: http://www.openbsd.org/cgi-bin/man.c...86&format=html. Then again, I guess your example is useful, if someone wants to know how strcpy() works :)

    strlcpy() is also useful, if you have it (the BSDs do, but not necessarily other OSs).
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    35
    Rep Power
    12
    Thanks for all your suggestion:

    I am already aware of strcpy and other functions in the standard library. Let me go into more detail.....

    I am reading in a text file which is formatted like (string1,string2,string3,....) then I am using the code below to put the individual strings into a Temp array.
    Code:
    char Temp[BIG ENOUGH];
    int element;
    FILE *in;
    FILE *out;
    
    
    while (!feof(in))    //start dissecting the input
    {	
    	element = 0;
    	key = fgetc(in);
    	while (key != ',')   //put all words into a temporary array
    	{
    	Temp [element] = key;
    		element++;
    		key = fgetc(in);
    	}
    		
    	Temp[element] = '\0';   //put '\0 at the end of a word
    		
    }
    now, each time we go through the inner while loop, I am putting a string (ex; string1) into Temp, which is big enough to hold string1, now I want to copy this string into its desired position (happens to be some row of a 2-dim char array) so that I can output it later.

    However, even though the 2-dim char Array....:
    Code:
    Array [NUM_ROWS][BIG ENOUGH];
    is big enough, I get the error : ('=' : left operand must be l-value) when I try ....
    Code:
    Array[ROW_N] = Temp;     //remember Array is 2-dim
    Also, when I try strcpy;
    Code:
    strncpy ( Array[ROW_N], Temp, 7);   //no compiling error 
    printf("%s", Array[ROW_N]);             //garbage comes out
    then, it prints a bunch of wierd characters.

    Please give me your insight into this problem....Thanks
  12. #7
  13. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    244
    Try this:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define BIG_ENOUGH 1024
    #define NUM_ROWS 10
    
    int main(){
        char Temp[BIG_ENOUGH];
        int i, element, rows, key;
        FILE *fin;
        char Array[NUM_ROWS][BIG_ENOUGH];
    
        if ((fin = fopen("test.txt", "r")) == NULL){
            fprintf(stderr, "Can't open test.txt!\n");
            exit(1);
        }
        rows = 0;
        while (!feof(fin)){    //start dissecting the input
    	    element = 0;
    	    key = fgetc(fin);
            while ((char)key != ',' && !feof(fin) && element < BIG_ENOUGH-1){
                //put all words into a temporary array
    	        Temp [element] = key;
    		    element++;
    		    key = fgetc(fin);
    	    }
    		    
    	    Temp[element] = '\0';   //put '\0 at the end of a word
            if (rows < NUM_ROWS){
                strcpy(Array[rows++], Temp);
            }
        }
        fclose(fin);
    
        for (i=0; i<rows; i++){
            fprintf(stderr, "%s\n", Array[i]);
        }
        return 0;
    }
    Contents of test.txt (no qoutes):

    "string1,string2,string3, string four, string 1234356"

    output from program:

    Code:
    string1
    string2
    string3
     string four
     string 1234356

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  14. #8
  15. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,225
    Rep Power
    2222
    You should also be aware of the theory behind mitakeet's suggestion.

    When you declare a 1-dimensional char array (eg, for a single string):
    char String [BIG ENOUGH];
    then String is a char* and String[ch] is a char.

    When you declare a 2-dimensional char array:
    char Array [NUM_ROWS][BIG ENOUGH];
    Then Array[row][ch] is of type char,
    Array[row] is of type char*, and
    Array is of type char** .

    So when you index a particular string within Array (eg, with Array[row]), then you are getting back a pointer to a string. Which is why you need to use strcpy to copy a string to that row:
    strcpy(Array[rows++], Temp);
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    35
    Rep Power
    12
    That does the trick:) Thanks mitakeet, dwise1.

    But, I have another question, I am using another file pointer to output the strings into another file (ie; I am not doing a print statement for my output).
    Anyhow, now that I have got my output nicely organized into a 2-dim array :D , when I do fputs:
    Code:
     FILE * out; out = fopen("output.txt", "w"); fputs(Array[row_num], out);
    some of the desired output does not make it to the output file.
    ie; I am working with a very large input file(over 10,000 words), but the output only displays about 9,000 of these words then quits.
    I get no compile time error, but using visual C++, I get one of those annoying error reports, every time I compile the program.
    Could this be because the words that I have in the arrays are not all big enough to fill the Array[TOO BIG];?
  18. #10
  19. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    244
    It is certainly possible, but the idea that the program will run with that much corruption in your program is rather unlikely. My guess is you may have inadvertantly written a NULL character to the output file (probably by attempting to print a NULL pointer). I have done that a few times and it has the effect of closing the file handle. Since the program does not complain if you write to a closed file handle, it will merrily go about its business. Try printing the data to stdout or stderr and then capturing to file to see if that makes any difference (stdout/stderr seems to be more resistant to such mistakes).

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw

IMN logo majestic logo threadwatch logo seochat tools logo