Sujet : Re: Suggested method for returning a string from a C program?
De : nospam (at) *nospam* dfs.com (DFS)
Groupes : comp.lang.cDate : 19. Mar 2025, 21:45:54
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vrfadv$1jska$2@dont-email.me>
References : 1 2 3
User-Agent : Betterbird (Windows)
On 3/19/2025 4:53 AM, Keith Thompson wrote:
Ike Naar <ike@sdf.org> writes:
On 2025-03-19, DFS <nospam@dfs.com> wrote:
I'm doing these algorithm problems at
https://cses.fi/problemset/list/
I've been playing with some of these myself.
Are you just looking for ones you find interesting?
I'm starting at the top and going down 1 by 1, no matter how simple.
I'm actually using
scanf() for integer input, something I wouldn't do in normal code
(because the behavior is undefined if the scanned value is out
of range). This is a rare case where it's safe to assume that
stdin has nothing harmful.
My very 1st submission for 'Missing Number' was accepted, but each use of scanf() generated a warning:
warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
30 | scanf("%d", &nums[i]);
spoiler: code below
===============================================================
//identify the missing number in a set of consecutive integers
#include <stdio.h>
#include <stdlib.h>
//comparator function used with qsort
int compareint (const void * a, const void * b)
{
if (*(int*)a > *(int*)b) return 1;
else if (*(int*)a < *(int*)b) return -1;
else return 0;
}
int main(int argc, char *argv[])
{
//vars
int i = 0, N = 0;
//line 1 from stdin: number of elements + 1
scanf("%d", &N);
int *nums = malloc(N * sizeof(int));
//line 2 from stdin: list of elements
for (i = 0; i < N-1; i++) {
scanf("%d", &nums[i]);
}
//sort the array
qsort(nums, N, sizeof(int), compareint);
//identify missing number
int missing = N;
for(i = 0; i < N; i++) {
if(nums[i+1] - nums[i] > 1) {
missing = nums[i] + 1;
break;
}
}
//print solution
printf("%d\n", missing);
//free and end
free(nums);
return 0;
}
===============================================================