给定两个排序的字符串,我需要将这些字符串合并为一个字符串,并将其排序。按ASCII值排序。例如:acdty,berz => abcdertyz
我的代码:
#include <stdio.h>
#include <stdlib.h>
char* PairSortedArrays(char a[], char b[]) {
char* c = (char*)malloc((sizeof(a) + sizeof(b)) * sizeof(char));
int i, aPos = 0, bPos = 0;
for (i = 0; i < sizeof(*c); i++) {
if ((int)(a[aPos]) <= (int)(b[bPos])) {
c[i] = a[aPos];
aPos++;
}
else {
c[i] = b[bPos];
bPos++;
}
}
return c;
}
int main()
{
printf("%s", PairSortedArrays("acdty", "berz"));
return 0;
}第一个问题是sizeof(a)。如果我编码:printf("%d", sizeof(a));,它会打印8,而我希望它会打印5。
发布于 2019-12-29 22:12:30
控制for循环的表达式for是罪魁祸首。您的程序的更正版本可以是:(我编辑了一些代码)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* PairSortedArrays(const char a[], const char b[])
{
size_t i;
const size_t total_len = strlen(a)+strlen(b);
char *c = malloc(total_len + 1);
size_t aPos = 0, bPos = 0;
for (i = 0; i < total_len; i++) {
if (a[aPos] == '\0') {
strcpy(c + i, b + bPos);
break;
}
if (b[bPos] == '\0') {
strcpy(c + i, a + aPos);
break;
}
c[i] = a[aPos] < b[bPos] ? a[aPos++] : b[bPos++];
}
return c;
}
int main()
{
printf("%s\n", PairSortedArrays("acdty", "berz"));
printf("%s\n", PairSortedArrays("az", "ks"));
return 0;
}必须在实际程序中对照NULL检查malloc的返回值。此外,还存在内存泄漏(易于修复)。
发布于 2019-12-29 21:15:33
在使用C中的字符串时,您可能希望使用strlen()来查看它们的长度,而不是sizeof (只告诉您指针的大小)。
还要注意,从定义上来说,sizeof(char)是1,所以在malloc中没有必要说"* sizeof(char)“
发布于 2019-12-29 21:19:53
在这种情况下,sizeof(a)将返回指针的大小,如果为64种体系结构编译,指针大小将为8字节。如果字符串为空终止,则必须传递每个字符串的大小或循环字符串字符,直到到达'\0'为止。
https://stackoverflow.com/questions/59523279
复制相似问题