Consider a 2D array of type char**. This array has a finite number of rows (number of substrings), but variable column length (variable substring length).
I would like to create a function that takes this array and number of rows (substrings) as parameters, and returns a single string that consists of each ordered substring (row). It it a simple concatenation. This is the opposite behaviour of this question.
I have written the following code to do so, but it only works if each substring is the same length (constant column length), and therefore I pass the maximum column length as a function parameter:
char* cat2dCharMat(char** A, int m, int n){
char* temp = malloc((m*n+1));
int length = 0;
for(int i = 0; i < m;++i){
memcpy(&temp[n*i], A[i],strlen(A[i]));
length += (int)strlen(A[i]);
}
temp[length] = '\0';
printf("Length of concatenated string is %d chars.\n",strlen(temp));
return temp;
}
How can I make this more general to take in many columns lengths? I also wrote a main() to accompany this function for a complete, minimum, verifiable example (forgive the 2D array initialization -- I found that using array = {"hello", "world!"} did not work):
int main(void){
char** array2 = (char**)malloc((3)*sizeof(char*));
for(int i = 0; i < 3; ++i){
array2[i] = (char*)malloc(4*sizeof(char));
for(int j = 0; j < 3;++j){
if(j==0 && i==0)
array2[i][j] = '0';
else if(j==1 && i==0)
array2[i][j] = '8';
else if(j==2 && i==0)
array2[i][j] = '7';
else if(j==0 && i==1)
array2[i][j] = '4';
else if(j==1 && i==1)
array2[i][j] = '9';
else if(j==2 && i==1)
array2[i][j] = '5';
}
}
char** array1 = (char**)malloc((3)*sizeof(char*));
for(int i = 0; i < 3; ++i){
if(i == 0){
array1[i] = malloc(4);
for(int j = 0; j < 3;++j){
if(j==0 && i==0)
array1[i][j] = '0';
else if(j==1 && i==0)
array1[i][j] = '8';
else if(j==2 && i==0)
array1[i][j] = '7';
}
}else{
array1[i] = malloc(5);
for(int j = 0; j < 4;++j){
if(j==0 && i==0)
array1[i][j] = '0';
else if(j==1 && i==1)
array1[i][j] = '8';
else if(j==2 && i==1)
array1[i][j] = '7';
else if(j==3 && i==1)
array1[i][j] = '7';
}
}
}
array1[0][3] = '\0';
array1[1][4] = '\0';
char* array1cat = cat2dCharMat(array1,2,4);
char* array2cat = cat2dCharMat(array2,2,3);
printf("Testing cat2dCharMat()...\n\n");
printf("Case 1: {\"087\",\"495\"}\n");
printf("Expected Result: 087495\n");
printf("Actual Result: %s\n", array2cat);
printf("Case 2:{\"087\",\"0877\"}\n");
printf("Expected Result: 0870877\n");
printf("Actual Result: %s\n", array1cat);
}