简体   繁体   English

使用递归函数反转结构化数组

[英]Reversing a structed array with a recursive function

So i got this struct所以我得到了这个结构

typedef struct Sarray{
  int *items;
  int size;
}Tarray;

Considering an array like [1][2][3][4][5]考虑像 [1][2][3][4][5] 这样的数组

i built a function like this我构建了一个这样的函数

void ArrayReverse (Tarray *a){
    int tmp,i;
    if (a->size<=1)
        return;
    tmp=(a->items[0]);
    (a->items[0])=(a->items[a->size]);
    (a->items[a->size])=tmp;
    a->size=a->size-1;

    ArrayReverse(a+1);
}

The result is weird结果很奇怪

0 2 3 4 5 0 2 3 4 5

The idea was to give the next address (a+1) so the a->items[0] would have been 2 in the second cycle.这个想法是给出下一个地址 (a+1),所以 a->items[0] 在第二个循环中应该是 2。 What's wrong how could i implement it ?我怎么能实现它?

In these statements在这些声明中

(a->items[0])=(a->items[a->size]);
(a->items[a->size])=tmp;

you access memory beyond the allocated array because the valid upper index is a->size - 1 .您访问分配的数组之外的内存,因为有效的上索引是a->size - 1

Instead of decreasing the data member size by one而不是将数据成员size减一

a->size=a->size-1;

you have to decrease it by two.你必须把它减少两个。

a->size=a->size-2;

Moreover the function changes the values of data members size and items of the original object passed as an argument.此外,该函数更改作为参数传递的原始对象的数据成员sizeitems的值。 So after exiting the function the state of the original object will be changed.所以退出函数后,原始对象的状态将发生变化。

And this expression还有这个表情

a+1

does not make sense because you passed to the function a pointer to a single object of the type Tarray .没有意义,因为您向函数传递了一个指向Tarray类型的单个对象的指针。

The function can look the following way as it is shown in the demonstrative program below.该函数可以如下所示,如下面的演示程序所示。

#include <stdio.h>
#include <stdlib.h>

typedef struct Sarray
{
    int *items;
    size_t size;
} Tarray;

void ArrayReverse ( Tarray *t )
{
    if ( ! ( t->size < 2 ) )
    {
        int tmp = t->items[0];
        t->items[0] = t->items[t->size - 1];
        t->items[t->size - 1] = tmp;

        t->size -= 2;
        ++t->items;

        ArrayReverse( t );

        t->size += 2;
        --t->items;
    }
}

int main(void) 
{
    Tarray t = { 0 };
    size_t n = 5;

    t.items = malloc( n * sizeof( int ) );

    if ( t.items != NULL ) t.size = n;

    for ( size_t i = 0; i < t.size; i++ )
    {
        t.items[i] = ( int )( i + 1 );
    }

    ArrayReverse( &t );

    for ( size_t i = 0; i < t.size; i++ )
    {
        printf( "%d ", t.items[i] );
    }

    putchar( '\n' );

    free( t.items );

    return 0;
}

The program output is程序输出是

5 4 3 2 1

The new version of the code is this one.新版本的代码就是这个。

void ArrayReverse (Tarray *a,int i){
int tmp;
if(a->size <= a->lenght/2)
    return;
tmp=a->items[i];
a->items[i]=a->items[a->size-1];
a->items[a->size-1]=tmp;
a->size=a->size-1;
i++;
ArrayReverse(a,i);}

I changed the prototype of the function with the counter i.我用计数器 i 更改了函数的原型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM