Thread: How to duplicating the Array & copy tokenPtr to an array

  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    35

    Question How to duplicating the Array & copy tokenPtr to an array

    Dear fellows, I have few questions here.

    (1) Duplicating the Array
    This is part of my code for duplicating the array from
    name[j] to secondname[x]

    Code:
                // Read from a file entered by user          while(fgets( name[j], 255, fpPtr )!=NULL){    
                    printf( "Name %s\n", name[j] );                // Verfication
                    strcpy( name[j], secondname[x] );    
                    printf( "Second name %s\n", secondname[x] );    // Verification
                    j++;
                    x++;
                }
    When I run the program, how comethe string for secondname[x] does not contain any value inside?


    (2) Copy tokenPtr to an array

    In the followings function prototype, I want to copy the string contain inside the token pointer to an array named tempsort[x], but this process was not success when I use the strcpy method, kindly show me the correct way of dealing with token pointer in the strtok.


    Code:
    void namesort ( char name[LEN][SIZE], int last ){       int  i, j, x;         // indices of array
        char *tokenPtr;    // create char pointer;
        char tempsort[LEN][SIZE];
    
    
        for (i = last ; i > 0 ; i--){
    
    
            for (j = 0 ; j <= last ; j++){
                printf("sorting %s",name[j]);    // For checking
                  for (x = 0 ; x <= last ; x++){
                    tokenPtr = strtok (name[j], ".");
                    while (tokenPtr != NULL){
                        printf("tokenPtr: %s\n", tokenPtr) ;    // For checking                
                        strcpy( tokenPtr,tempsort[x] );            // assint tokenPtr to tempsort
                        printf("tempsort: %s\n", tempsort[x]) ;    // For checking                            
                        tokenPtr = strtok ( NULL, ".");            // get next token    
                    }    // end while
    //                    printf("%s",name[j]) ;    // For checking
                }
            }
        }
    }     // End function prototype

    Thanks in advance
    Attached Files Attached Files
    Last edited by Watervase Chew; 04-16-2013 at 08:34 AM. Reason: Attach the source code file

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    505
    Your central problem is that strcpy() takes the destination as its first argument not, as might be more logically expected, its second.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    When I run the program, how comethe string for secondname[x] does not contain any value inside?
    Perhaps you have your source and destination strings reversed? Did you read the documentation for the strcpy() function?

    Jim

  4. #4
    Registered User
    Join Date
    Apr 2013
    Posts
    35
    Quote Originally Posted by Malcolm McLean View Post
    Your central problem is that strcpy() takes the destination as its first argument not, as might be more logically expected, its second.
    Quote Originally Posted by jimblumberg View Post
    Perhaps you have your source and destination strings reversed? Did you read the documentation for the strcpy() function?

    Jim
    Looks like I had made a mistake in the strcpy.
    I had correct their position. But now the compiler showing these error:

    manual5.c: In function ‘main’:
    manual5.c:38:5: warning: passing argument 1 of ‘strcpy’ from incompatible pointer type [enabled by default]
    /usr/include/string.h:128:14: note: expected ‘char * __restrict__’ but argument is of type ‘char (*)[255]’
    manual5.c:38:5: warning: passing argument 2 of ‘strcpy’ from incompatible pointer type [enabled by default]
    /usr/include/string.h:128:14: note: expected ‘const char * __restrict__’ but argument is of type ‘char (*)[255]’


    manual5.c

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    Post your modified code. Also show how these variables were defined.

    Jim

  6. #6
    Registered User
    Join Date
    Apr 2013
    Posts
    35
    Dear Malcolm McLean and Jim, looks like I am confusing with the name[j] and name, I had missed the [j] in the strcpy, that's why showing warnings during compilation.

    Thanks

  7. #7
    Registered User
    Join Date
    Apr 2013
    Posts
    35
    Quote Originally Posted by jimblumberg View Post
    Post your modified code. Also show how these variables were defined.

    Jim


    Code:
    // Read text from filenames entered by user OR text input from user and
    // sort in alphabetical format.
    
    
    #include <stdio.h>
    #include <string.h>
    #define SIZE 255
    #define LEN  255
    
    
    void namesort ( char name[LEN][SIZE], int last );
    void showSortingResult ( char name[LEN][SIZE], int last );
    
    
    // Function main begins program execution
    int main(int argc, char * argv[])
    {
    	char name[LEN][SIZE];
    	char secondname[LEN][SIZE];
    	int  i,j=0, x=0;    	// indices of array
    	int  f;				// file counter
      	int  last; 			// index of last item in array 
       	FILE *fpPtr; 		// fpPtr is pointer
    
    
    	// if there is a filename from commandline
    	if ( argc > 1 ) {                  	 	
    		for (f=1; f<=argc-1; f++){
    		
    		/* This part for file input verification
    				if(f==1)								
    					printf("%s\n",argv[1]);
    				else
    					printf("%s\n",argv[2]);      */
    
    
    			// fopen opens file, Read text from a filename entered by user         
     			fpPtr = fopen ( argv[f], "r" ); 	
    
    
    			// Read from a file entered by user
          	while(fgets( name[j], 255, fpPtr )!=NULL){	
    				printf( "Name %s\n", name[j] );				// Verfication
    				strcpy( secondname[x], name[j] );	
    				printf( "Second name %s\n", secondname[x] );	// Verification
    				j++;
    				x++;
    			}
    
    
    		fclose( fpPtr ); // Closes the file
    		}	// end for
    
    
    		// Sent to namesorting Function Prototype to sort by symbol, A-Z. a-z
    		printf("\n---- Sorting Process  ---- \n");		//Verification		
    		namesort ( name, j-1 );				
    	
    		// Output result using Function prototype
    		printf("\n---- Display the result  ---- \n");	//Verification	
    		showSortingResult ( name, j-1 );	
    
    
    		printf("\n---- End of file input part ---- \n");//Verification
    	}	// end if
    
    
    	else {
    
    
    		// Get manually entered data from user
        	fpPtr = stdin;								
    
    
    		for(j = 0 ; !feof( fpPtr ) ; j++ ){	
    			// Read next record
    			fgets( name[j], 255, fpPtr );   	
    		}
    
    
    		// Sent to namesorting Function Prototype to sort by symbol, A-Z. a-z
    		printf("\n---- Sorting Process  ---- \n");		//Verification		
    		namesort ( name, j );
    
    
    		// Output result using Function prototype
    		printf("\n---- Display the result  ---- \n");	//Verification	
    		showSortingResult ( name, j );	
    
    
    		printf("\n---- End of manually input part ---- \n");	//Verification
    	}	// end if else 
    
    
      	return 0; 
    } 	// End Main
    
    
    
    
    // Function to Sorting by symbol, A-Z, a-z
    void namesort ( char name[LEN][SIZE], int last ){
       	int  i, j, x; 		// indices of array
    	char *tokenPtr;	// create char pointer;
    	char tempsort[LEN][SIZE];
    
    
    	for (i = last ; i > 0 ; i--){
    
    
    		for (j = 0 ; j <= last ; j++){
    			printf("sorting %s",name[j]);	// For checking
    		  	for (x = 0 ; x <= last ; x++){
    				tokenPtr = strtok (name[j], ".");
    				while (tokenPtr != NULL){
    					printf("tokenPtr: %s\n", tokenPtr) ;	// For checking				
    					strcpy( tempsort[x], tokenPtr );			// assint tokenPtr to tempsort
    					printf("tempsort: %s\n", tempsort[x]) ;	// For checking							
    					tokenPtr = strtok ( NULL, ".");			// get next token	
    				}	// end while
    //					printf("%s",name[j]) ;	// For checking
    			}
    		}
    	}
    } 	// End function prototype
    
    
    
    
    // Function to Printf result
    void showSortingResult ( char name[LEN][SIZE], int last ){
    	int  i; 		// indices of array
    
    
    	//	Write array to output
    	for (i = 0 ; i <= last ; i++)	
    		printf("%s",name[i]) ;	// For checking
    
    
    } 	// End function prototype

  8. #8
    Registered User
    Join Date
    Apr 2013
    Posts
    35
    My next steps will be sorting the data from either inside a text file OR entered manually in the following format. Any idea about it?

    line3text1.line3text2.line3text3
    line2text1.line2text2.line2text3
    line1text1.line1text2.line1text3

    Will sort become:

    line1text3.line1text2.line1text1 -->
    with sorting priority from the right hand side
    line2text3.line2text2.line2text1
    line3text3.line3text2.line3text1

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    Why are you separating your "strings" with a period instead of a space?

    Do your "strings" have embedded spaces within them? If not, using a space will make separating the data much easier.

    Jim

  10. #10
    Registered User
    Join Date
    Apr 2013
    Posts
    35
    Quote Originally Posted by jimblumberg View Post
    Why are you separating your "strings" with a period instead of a space?

    Do your "strings" have embedded spaces within them? If not, using a space will make separating the data much easier.

    Jim
    The input strings consist of data separate with period only. Actually the input data are same like the web address (i.e. cboard.cprogramming.com). It looks like much more difficult to sort them, because they must be sorted from the right hand side instead of the usual way from left hand side

  11. #11
    Registered User
    Join Date
    Apr 2013
    Posts
    35
    This is my updated code for the sorting function:

    Compiled with errors
    Code:
    // Function to Sorting by symbol, A-Z, a-z
    void namesort ( char name[LEN][SIZE], int last ){
      	int  i, j, x; 		// indices of array
    	char *tokenPtr;	// create char pointer;
    	char tempsort[LEN][SIZE];
    
    
    //	for (i = last ; i > 0 ; i--){			// Loop = total of lines
    
    
    		for (j = 0 ; j <= last ; j++){
    
    
    //		  	for (x = 0 ; x <= last ; x++){
    
    
    				// for checking
    				printf( "Name %s\n", name[j] );
    
    
    				tokenPtr = strtok (name[j], ".");	// Remove period
    				while (tokenPtr != NULL){
    
    
    					// for checking
    					printf( "tokenPtr: %s\n", tokenPtr );
    
    
    					strcpy( tempsort[x], tokenPtr );			// Copy tokenPtr to tempsort
    
    
    					// for checking
    					printf( "tempsort: %s\n", tempsort[x] ); 
    
    
    					tokenPtr = strtok ( NULL, ".");			// get next token	
    				}	// end while
    					x++;
    
    
    					// for checking
    					printf( "Name 2nd %s\n", name[j] );
    
    
    //			}		// x Loop
    		}		// j Loop
    //	}		//	Loop = total of lines
    } 		// End function prototype

    This is my input data:

    abc.example.co.jp
    abc.example.or.jp
    xy.example.JP
    example.org
    info
    abc.example.com
    example.co.jp
    XY.Example.com
    xy.example.ac.jp
    abc.example-2.ac.jp

    These input must be sort from the back of every string that are separated with period into:

    abc.example.com
    XY.Example.com
    info
    xy.example.ac.jp
    abc.example-2.ac.jp
    example.co.jp
    abc.example.co.jp
    xy.example.JP
    abc.example.or.jp
    example.org

  12. #12
    Registered User
    Join Date
    Apr 2013
    Posts
    35

    Question Error in Sorting

    Dear all, I want to the split the name array (up to total n numbers of them, n = last) into smaller sub name and place them into 2D array.

    The code below looks like cannot loop properly, is there anyone to provide some tips?

    Thanks!!

    Code:
    // Function to Sorting by symbol, A-Z, a-z
    void namesort ( char name[LEN][SIZE], int last ){
      	int  i, j, x; 			// indices of array
    	char *tokenPtr;		// create char pointer;
    	char tempsort[LEN][SIZE];
    
    
    	for (i = last ; i > 0 ; i--){			// Loop = total of lines
    		for (j = 0 ; j <= last ; j++){
    		  	for (x = 0 ; x <= last ; x++){
    	
    				tokenPtr = strtok (name[j], ".");	// Remove period
    				while (tokenPtr != NULL){
    					
    						strcpy( tempsort[x], tokenPtr );			// Copy tokenPtr to tempsort
    						tokenPtr = strtok ( NULL, ".");			// get next token	
    						x++;	// increment the array x
    						}	// end for
    
    
    			}	// end x loop
    		}	// j Loop
    	}	// i Loop
    }	// End function prototype

  13. #13
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by Watervase Chew View Post
    The code below looks like cannot loop properly, is there anyone to provide some tips?
    You overwrite "tempsort" in every iteration of your outer for-loops

    But instead of fixing your broken code I suggest you think again how you want to tackle your problem:
    Quote Originally Posted by Watervase Chew View Post
    This is my input data:

    abc.example.co.jp
    abc.example.or.jp
    xy.example.JP
    example.org
    info
    abc.example.com
    example.co.jp
    XY.Example.com
    xy.example.ac.jp
    abc.example-2.ac.jp

    These input must be sort from the back of every string that are separated with period into:

    abc.example.com
    XY.Example.com
    info
    xy.example.ac.jp
    abc.example-2.ac.jp
    example.co.jp
    abc.example.co.jp
    xy.example.JP
    abc.example.or.jp
    example.org
    My approach would be to store each input into a struct with two members: "original_string" and "sorting_string" where "sorting_string" is a modified string used for the sorting. E.g. for your first line "original_string" would be "abc.example.co.jp" and "sorting_string" would be "jpcoexampleabc". Then you can easily sort your data using "sorting_string" as the sort key.

    You need of course write a function which transforms each "original_string" into a "sorting_string" (e.g. using strtok()).

    Bye, Andreas

  14. #14
    Registered User
    Join Date
    Apr 2013
    Posts
    35

    Question

    Quote Originally Posted by AndiPersti View Post
    You overwrite "tempsort" in every iteration of your outer for-loops

    But instead of fixing your broken code I suggest you think again how you want to tackle your problem:


    My approach would be to store each input into a struct with two members: "original_string" and "sorting_string" where "sorting_string" is a modified string used for the sorting. E.g. for your first line "original_string" would be "abc.example.co.jp" and "sorting_string" would be "jpcoexampleabc". Then you can easily sort your data using "sorting_string" as the sort key.

    You need of course write a function which transforms each "original_string" into a "sorting_string" (e.g. using strtok()).

    Bye, Andreas
    Hi there, at first I thought of using strtok to remove all the period symbol first and place every small part (i.e. abc) of the main string (abc.example.co.jp) into 2D array, then compare the final string back checking the total numbers of sub string in every row. But looks like this is too complicate to execute...

  15. #15
    Registered User
    Join Date
    Apr 2013
    Posts
    35
    Found an useful function here to reverse my string...
    Reverse words in a given string - GeeksforGeeks | GeeksforGeeks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. why can't a static array copy values from a dynamic array
    By c++noob145 in forum C++ Programming
    Replies: 2
    Last Post: 03-13-2013, 10:25 AM
  2. Copy array into a Dynamic array
    By pantherman34 in forum C Programming
    Replies: 15
    Last Post: 05-01-2010, 10:58 PM
  3. Duplicating specific binary data in array
    By chris.lloyd in forum C Programming
    Replies: 1
    Last Post: 10-21-2006, 09:54 PM
  4. Copy multidimensional array to single array?
    By seepox in forum C Programming
    Replies: 9
    Last Post: 05-08-2006, 11:19 AM
  5. Help to copy Array a into first portion of array b
    By Anna Lane in forum C Programming
    Replies: 4
    Last Post: 11-25-2002, 09:38 PM

Tags for this Thread