我从学校接到一项任务,要从2个不同的数组中创建一个数组,并返回组织好的组合数组。
示例:arr a [] = {“ ace”}arr b [] = {“ bdf”}
必填结果:arr x [] = {“ abcdef”}
到目前为止,我设法将两者合并并重新排序,但是在编译代码时偶尔会在数组末尾返回不同的值(代码中的var p
)。 >
我写的代码:
int main() { char a[] = { "1D5"}; char b[] = { "+J6" }; int size_a = sizeof(a); int size_b = sizeof(b); char *p = NULL; //setting the pointer for the start of the array as null int total_arr_size = size_a + size_b; int index = 0; p = (char*)malloc((total_arr_size-1) * sizeof(char)); if (!p) { printf("Allocation error"); exit(1); } while (index <= total_arr_size-2) { if (index < size_a && a[index] != '\0') { p[index] = a[index]; index++; continue; } if (index < (size_a + size_b) - 2 ) { p[index] = b[index-size_a+1]; index++; continue; } break; } printf("total string before sorting - %s \n", p); int i, j; int n = total_arr_size - 2; int temp; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (p[i] > p[j]) { temp = p[i]; p[i] = p[j]; p[j] = temp; } } } printf("String after sorting - %s \n", p); free(p); p = NULL; return 0; }
我希望
p
返回值+156DJ
。
我从学校接到一项任务,要从2个不同的数组中创建一个数组,并返回组织好的组合数组。示例:arr a [] = {“ ace”} arr b [] = {“ bdf”}所需结果:arr x [] = ...
您使生活变得困难。以下简单得多: