简体   繁体   中英

Passing function output isn't correct in C

This program will ask user for numbers, and then will sort them, and display how many triplets are in the array. If i enter {1,2,3,3,3,4,5,3,3,6,7}, it will be 3 triplets.

I don't know what happens in my void triplet(int count, int uin[]) function; it is not working. Please help me to fix this.

#include "stdafx.h"
#include <stdio.h>

void sorting(int count, int uin[]);
void triplet(int count, int uin[]);

int uin[30];
int i;
int done;
int count = 0;

int main()
{
    for (i = 0; i < 30; i++)
    {
        printf("plase input the number: ");
        done = scanf_s("%d", &uin[i]);

        if (done != EOF)
        {
            count++;
        }
        else
        {
            break;
        }
    }
    sorting(count, uin);
    triplet(count, uin);
    return 0;
}    

void sorting(int count, int uin[])
{
    int i, j, temp;
    for (i = 0; i < count; i++)
    {
        for (j = 0; j < count - 1; j++)
        {
            if (uin[i]<uin[j])
            {
                temp = uin[i];
                uin[i] = uin[j];
                uin[j] = temp;
            }
        }
    }
}    

void triplet(int count, int uin[])
{
    int i;
    int counter = 0;
    for (i = 0; i < count; i++)
    {
        if (uin[i] == uin[i + 1] && uin[i + 2])
        {
            counter++;
        }
        printf("\n%d\n", counter);
    }
}

uin[i] == uin[i + 1] && uin[i + 2] should be uin[i] == uin[i + 1] && uin[i] == uin[i + 2] . Study these two carefully and make sure you understand the difference!

Also, as Joachim pointed out, the loop condition should be i < count - 2 .

Usually when arrays are used as parameters of functions then the first parameter is the array itself and the second parameter is the number of elements in the array. So instead of

void triplet(int count, int uin[]);

I would declare the function the following way

void triplet( const int uin[], int n );

Your function definition is invalid. First of all it uses invalid condition in if statement

if (uin[i] == uin[i + 1] && uin[i + 2])

and secondly there is an attempt to access memory beyond the array.

The function could be defined as

void triplet( const int uin[], int n )
{
    int i;
    int counter = 0;

    for ( i = 0; i + 2 < n; i++ )
    {
        counter += uin[i] == uin[i + 1] && uin[i + 1] == uin[i + 2];
    }

    printf( "\n%d\n", counter );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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