Nicht C89-konformen Code zu schreiben ist immer ein Grund, zumindest im Fegefeuer zu landen.
na servas, da gehts ja ganz genau her :shinner:. so besser?
C
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char **argv)
{
int i;
char *endptr;
long *ar;
ar = (long *) malloc ( (argc - 1) * sizeof(long));
if (ar == NULL)
{
fprintf(stderr, "Cannot allocate memory\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < argc-1; i++)
{
errno = 0;
ar[i] = strtol(argv[i+1],&endptr,10);
if ((errno == ERANGE && (ar[i] == LONG_MAX || ar[i] == LONG_MIN))
|| (errno != 0 && ar[i] == 0))
{
free(ar);
perror("strtol");
exit(EXIT_FAILURE);
}
if (endptr == argv[i+1])
{
free(ar);
fprintf(stderr, "Not a digit: %s\n",endptr);
exit(EXIT_FAILURE);
}
if (*endptr != '\0')
{
printf("Further characters after number: %s\n", endptr);
}
}
for (i = 0; i < argc-1; i++)
{
printf("%ld\n",ar[i]);
}
/* free the whales, free the mallocs */
free(ar);
return 0;
}
Alles anzeigen