sannic19
sannic19

Reputation: 1

Need to copy string array into a pointer string array

I am writing a program that takes in a string array and sorts it then uses searching functions to search for a target. The string array I have set up works for all my sorting functions but I need the data to be in a pointer string array in order to make use of strcmp in my searching functions. I've attached the most recent attempt in my main function. The rest of the main function includes the sorting and searching function but what I am posting only contains the initialization of the arrays and printing them out. In the actual program, it will be copying the contents from the sorted array after whichever sorting function the user chooses completes. I just want to find out how I would copy the contents.

int main(void) {
    char arr[][MAX_LEN] = {"AAAAA", "a", "AAA", "aaaa", "AAa", "AAAAa", "AAa", "A", "aa", "Aaa"}; // initializes string array 
    char *target[] = {"A"};  //initializes target
    int n = sizeof(arr)/sizeof(arr[0]);  // initializes n 
    char *arry = (char* )malloc(n); // initizlizes *arry
    int i; 

    printf("Given string array is:");
    for (i = 0; i < n; i++)
        printf(" %s ", arr[i]); // prints out arr

    for (i = 0; i < n; i++) { // this was my first attempt to copy arr into *arr. 
        strcpy(arry[i], arr[i]);

        printf(" %s ", arry[i]); // used for testing to see if copying worked.
    }
}

Upvotes: 0

Views: 562

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

In this declaration

char *arry = (char* )malloc(n);

there is allocated only a buffer for n characters.

What you want to do is

char ( *arry )[MAX_LEN] = (char* )malloc( sizeof( char[n][MAX_LEN] ) );

Another approach is the following.

char **arry = malloc( n * sizeof( char * ) );

for ( size_t i = 0; i < n; i++ )
{
    arry[i] = malloc( sizeof( char[MAX_LEN] ) ); 
}

In any case you will need to free all allocated memory.

In the first case you can just write

free( arry );

In the second case you have to write

for ( size_t i = 0; i < n; i++ )
{
    free( arry[i] );
}

free( arry );

Upvotes: 1

Related Questions