Copy Array string to another Pointer array string in ANSI-C 
Author Message
 Copy Array string to another Pointer array string in ANSI-C

Dear all,

I need your help in urgently!
My main purpose is to copy strings, which stored in array, to a
pointer string array. Initially, the strings are gotten from TXT file
and then stored in array.
Does any one help me to correct it??
Thank you very much!!
Alan

This is my C program!!

int i, idx=0;
char cmp_name[100];
char *cmp_name[100];

        if ((stream_component_name = fopen("C:\\temp\\a.txt","r")) !=
NULL)
        {
                while (!feof(stream_component_name))
                {
                        fgets(cmp_name, 30, stream_component_name);
                        if (cmp_name != NULL)                                                           {
                                strcpy(*(cmp_name_p + idx), &cmp_name[idx]);
                                idx++;
                        }
                }
                fclose(stream_component_name);
        }

        for (i = 0; i < 100; i++)
        {
                printf("%s\n",cmp_name_p);
        }



Tue, 24 May 2005 18:32:14 GMT  
 Copy Array string to another Pointer array string in ANSI-C
Hi,

Quote:
> int i, idx=0;
> char cmp_name[100];
> char *cmp_name[100];            /* You probably mean char

*cmp_name_p[100]; */

Quote:

>         if ((stream_component_name = fopen("C:\\temp\\a.txt","r")) !=
> NULL)
> {
> while (!feof(stream_component_name))
> {
> fgets(cmp_name, 30, stream_component_name);
> if (cmp_name != NULL) {

/*  You should allocate the memory to store your string: */
   cmp_name_p[idx] = (char *)malloc(strlen(cmp_name));

/* Next you can copy the string to this location */
   strcpy(cmp_name_p[idx], cmp_name);

Quote:
> idx++;

/* Make sure you not run out of array boundaries: */

  if(idx >= 100)
      break;

Quote:
> }
> }
> fclose(stream_component_name);
> }

> for (i = 0; i < 100; i++)
> {
> printf("%s\n",cmp_name_p);  /* -- Wrong! Correct is: */

   if(cmp_name_p[i])
      printf("%s\n",cmp_name_p[i]);

Quote:
> }

/* Last, you should free the memory allocated! */

for(i = 0; i < 100; i++)
{
   if(!cmp_name_p[i])
      break;
   free(cmp_name_p[i]);

Quote:
}

SD


Tue, 24 May 2005 19:43:29 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. convert list to array, arrays of pointers (to strings)

2. Pointer to Array of Pointers to Strings.

3. Copying a string to an array element

4. copying elements from argv[] to array of strings ?

5. Having problems copying a string array.

6. Copy string to byte array in C#...

7. Problem of Return Array String to Main Program in ANSI-C

8. finding the closest match of a string compared to an array of strings

9. Putting strings into arrays of strings

10. Arrays and arrays of strings problem

11. String Arrays and string parsing

12. How To pass 2D String array to VB from VC++ Using Safe array

 

 
Powered by phpBB® Forum Software