Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have to write a program which accepts n number of integers and display the degree of the array

I’ve been trying to code this for the last hour but I keep on getting "segmentation error". I’m still very new to C so please don’t be too harsh. Can anybody help?

Here is my code:

input:4 2 4 2 2 5 6
output: 3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

int degreeOfArray(int arr[], int n)
{
    int maxnum = -100000;
    int currentN = 0;
    int res;
    for(int i = 0; i < n; i++)
    {
        currentN = 0;
        for(int j = 0; j < n; j++)
        {
            if(arr[i] == arr[j])
            {
                currentN++;
            }
        }
        if(currentN > maxnum) /*if the current is greater than max, current is max*/
        {
            maxnum = currentN;
            res = arr[i];
        }
    }
    return res;
}

int main(int argc, char**argv)
{
    argv++;
    int n = argc - 1;
    int arr[n];
    for(int i = 0; i < n; i++)
    {
        arr[i] = atoi(argv[i + 1]);
    }
    printf("%d\n", degreeOfArray(arr, n));
}

>Solution :

This is kind of naughty:

int main(int argc, char**argv)
{
    argv++;
    int n = argc - 1;
    int arr[n];
    for(int i = 0; i < n; i++)
    {
        arr[i] = atoi(argv[i + 1]);
    }
    printf("%d\n", degreeOfArray(arr, n));
}
  • Argc is 4.
  • You increment argv (which is naughty).
  • n is 3.
  • arr has values [0] through [2]
  • You loop from 0..2 (which is fine)
  • You set arr[i] just fine, but the call atoi(argv[i+1]) is a problem.

I is going to reach 2. so you’re hitting argv[3]. Which would be fine if you hadn’t incremented argv.

So either get rid of the i+1 there or don’t increment argv.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading