0

I found quiet tricky in copying string from two dimensional array to one dimensional array. So I made access those value by address. It is working fine inside for loop. Is the one-dimensional array is really copied with two-dimensional array value.

char *str[4] = {"i " "California", "ii " "Texas", "iii " "Florida", "iv " "Washington"};        //two dimensional array
int r = 0, c, i = 0;
char *temp;      //one dimesional array

for(r = 0; r < 4; r++){
    c = 0;
    while(*(str[r]+c) != '\0'){
        printf("%c", *(str[r]+c));
        c++;
        temp = &str[r][c];
        printf("%c", *temp);
    }
    printf("\n");
}

return 0;

2 Answers 2

1

You can use calloc for allocation temp pointer memory size.

#include<stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
    char *str[4] = {"i " "California", "ii " "Texas", "iii " "Florida", "iv " "Washington"};        //two dimensional array
    int r = 0;

    for(r = 0; r < 4; r++)
    {
        char *temp = (char*) calloc (strlen(str[r]) ,sizeof(char));
        strcpy(temp, str[r]);
        printf("%s", str[r]);
        printf("\n");
        free(temp);
    }
    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

in C, the returned type from any of the heap allocation functions: calloc realloc malloc 1) has type void* which can be assigned to any other pointer. Casting just clutters the code making it more difficult to understand, debug, etc. suggest removing the cast. 2) always check (!=NULL) the returned value to assure the operation was successful.
0

assuming:

char array2dim[x][y];

then to create a 1 dimensional array..

char array1dim[x*y];

memcpy( array1dim, array2dim, x*y );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.