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
#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.