gpt4 book ai didi

c - 每次编译参数返回不同的值

转载 作者:行者123 更新时间:2023-11-30 14:33:15 24 4
gpt4 key购买 nike

我收到了学校的作业,要从 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

最佳答案

你让你的生活变得太困难了。下面的内容就简单多了:

int main() {

char a[] = { "1D5"};
char b[] = { "+J6" };
int len_a = sizeof(a)-1;
int len_b = sizeof(b)-1;
char *p;
int index = 0;

if (!(p = malloc(len_a + len_b + 1))) {
printf("Allocation error\n");
exit(1);
}
for (int i=0; i<len_a; i++, index++)
p[index]= a[i];

for (int i=0; i<len_b; i++, index++)
p[index]= b[i];

p[index]= '\0';

printf("total string before sorting - %s \n", p);

// ....

关于c - 每次编译参数返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com