从C中的数组中删除偶数 [英] Remove even numbers from array in c

查看:433
本文介绍了从C中的数组中删除偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试大约2个小时来创建一个程序,该程序将从c中的dinamyc分配的数组(带有malloc)中删除偶数.有人可以帮我一些提示或创建代码.

Hello i'm trying for about 2 hours to create a program which will remove even numbers from a dinamyc allocated array(with malloc)in c.Can somebody help me with some tips or create the code.

p.s.这是我的第一个话题,请随时给我一些有关如何正确发布问题的提示.

p.s. this is my first topic here, so feel free to give me some tips about how to correctly post a qustion.

推荐答案

让我们假设您已经动态分配了n个元素的数组并对其进行了初始化.

Let's assume that you already allocated dynamically an array of n elements and initialized it.

在这种情况下,删除具有偶数值的元素的函数可以看起来如下

In this case the function that removes elements with even values can look the following way

size_t remove_even( int *a, size_t n )
{
    size_t m = 0;

    for ( size_t i = 0; i < n; i++ )
    {
        if ( a[i] % 2 != 0 )
        {
            if ( i != m ) a[m] = a[i];
            ++m;
        }
    }

    return m;
}

可以通过以下方式调用

size_t m = remove_even( p, n );

for ( size_t i = 0; i < m; i++ ) printf( "%d ", a[i] );
printf( "\n" );

其中p是指向动态分配的n个元素数组的指针.

where p is the pointer to your dynamically allocated array of n elements.

该函数实际上不会删除任何内容.它只是将奇数元素移到数组的开头.

The function actually removes nothing. It simply moves odd elements to the beginning of the array.

然后可以使用标准C函数realloc物理上删除已删除的元素.

You can then use standard C function realloc to delete physically the removed elements.

例如

int *tmp = realloc( p, m * sizeof( int ) );

if ( tmp != NULL ) p = tmp;

这是一个演示程序

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

size_t remove_even( int a[], size_t n )
{
    size_t m = 0;

    for ( size_t i = 0; i < n; i++ )
    {
        if ( a[i] % 2 != 0 )
        {
            if ( i != m ) a[m] = a[i];
            ++m;
        }
    }

    return m;
}

#define N   10

int main( void )
{
    int *a = malloc( N * sizeof( int ) );

    for ( size_t i = 0; i < N; i++ ) a[i] = i;

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    printf( "\n" );

    size_t m = remove_even( a, N );

    int *tmp = realloc( a, m * sizeof( int ) );

    if ( tmp != NULL ) a = tmp;

    for ( size_t i = 0; i < m; i++ ) printf( "%d ", a[i] );
    printf( "\n" );

    free( a );
}

其输出为

0 1 2 3 4 5 6 7 8 9 
1 3 5 7 9 

这篇关于从C中的数组中删除偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆