c语言 - 我正在尝试使用指针合并两个排序(int)数组,并且由于某种原因它存储了地址


void interclas(int *ptr,int *vec, int *c, int n) {
int i,j,tmp;
tmp=0;
for (i=0;i++;i<n)
for (j=0;i++;j<n)
{
if (vec[j]<=ptr[i])
c[tmp]=vec[j];
else
c[tmp]=ptr[i];
tmp++;
}
}
int main() {
int i,n;
int *ptr,*vec,*c;
printf("Nr. of elements of initial arrays : 5 n");
n=5;
vec=(int*)malloc( n * sizeof(int));
ptr=(int*)malloc( n * sizeof(int));
c=(int*)malloc( 2 * n * sizeof(int));
for (i=0;i<n;i++) {
scanf("%d",&ptr[i]);
}
for (i=0;i<n;i++) {
scanf("%d",&vec[i]);
}
printf("n");
printf("Initial arrays are : ");
for (i=0;i<n;i++) {
printf("%d ",ptr[i]);
}
printf("n");
for (i=0;i<n;i++) {
printf("%d ",vec[i]);
}
interclas(ptr,vec,&c,n);
printf("Merged array is : ");
for (i=0;i<10;i++) {
printf("%d ",c[i]);
}
return 0;
}

所以我正在尝试使用带有函数"interclas"的指针将两个排序的数组合并为一个新的数组。我尝试使用相同的方法对函数中带有指针的数组进行排序,它工作得很好。现在如您所见,它存储变量的地址而不是变量本身。 如果我运行它,它会存储数组的地址。我该如何解决这个问题?(我还是新手(

在方法的主体中,更改:

for (i=0;i++;i<n)
for (j=0;i++;j<n)

对此:

for (i=0; i<n; i++)
for (j=0; j<n; j++)

然后将调用更改为您的方法,从这里:

interclas(ptr, vec, &c, n);

对此:

interclas(ptr, vec, c, n);

由于原型需要指向第三个参数的指针指向int


你的方法的逻辑也有缺陷,试着放一些printfs(例如printf("here i = %d, j = %d, ptr[i] = %d, vec[j] = %d, tmp = %dn", i, j, ptr[i], vec[j], tmp);( 以查看变量在迭代时具有哪些值 - 您只能合并第一个数组的前两个元素!

如果你考虑一下,你想做的是遍历数组的第一个元素ptrvec,并存储这两个元素中的最小值。如果现在 min 是数组ptr,您希望考虑ptr的下一个元素,否则考虑vec的下一个元素。

拿一支铅笔和一张纸,画出这个算法 - 你会看到它很好,但一些剩余的元素可能会留下来,而不是插入到输出数组中。

根据该观察结果,在遍历两个数组并比较元素之后,如果需要,我们将遍历第一个数组,以收集未访问的元素。第二个数组也是如此。

编码这个想法会得到这样的东西:

void interclas(int *ptr,int *vec, int *c, int n) {
int i = 0, j = 0, tmp = 0;
// Traverse both arrays simultaneously,
// and choose the min of the two current elements.
// Increase the counter of the array who had
// the min current element.
// Increase the counter for the output array in
// any case.
while(i < n && j < n)
{
if(ptr[i] < vec[j])
{
c[tmp++] = ptr[i++];
}
else
{
c[tmp++] = vec[j++];
}
}
// Store remaining elements of first array 
while (i < n) 
c[tmp++] = ptr[i++]; 
// Store remaining elements of second array 
while (j < n) 
c[tmp++] = vec[j++]; 
}

不是你问题的根源,但我是否投射了 malloc 的结果?不。

最新更新