I'm trying to solve some simple problem.
There is an input file equal.in
. It consists of two lines: first one contains the number N of numbers in next line. Second line contains N numbers separated by single space. N is not greater than 3 * 10^5, each number is not greater than 10^9.
I'm trying to solve this program using C language. I've already made it in python like in 1 minute or so, however i struggle in C. I've made a function read_file
, which should return a pointer to the array of long
numbers and also change the value of size
variable. The program runs smoothly while the number N is less than 10^4, when it's above that, the array is filled with zeroes except the first element. What am I doing wrong?
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_NUMBERS 300000
#define MAX_VALUE 1000000000
long* read_file(char*, long*);
int number_width(int);
int main() {
long i, size;
long* numbers = read_file("equal.in", &size);
printf("Size: %d\n", size);
printf("Array: ");
for (i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
free(numbers);
return 0;
}
long* read_file(char* filename, long* size) {
FILE* in_file = fopen(filename, "r");
long l1_width = number_width(MAX_NUMBERS);
char* line1 = malloc(sizeof(char) * l1_width);
fgets(line1, l1_width, in_file);
char *ptr;
*size = strtol(line1, &ptr, 10);
free(line1);
long* numbers = malloc(sizeof(long) * *size);
long l2_width = (number_width(MAX_VALUE) + 1) * *size;
char* line2 = malloc(sizeof(char) * l2_width);
fgets(line2, l2_width, in_file);
char* token = strtok(line2, " ");
int i = 0;
while (token != NULL) {
*(numbers+i) = strtol(token, &ptr, 10);
token = strtok(NULL, " ");
i++;
}
free(line2);
fclose(in_file);
return numbers;
}
int number_width(int n) {
if (n < 0) n = (n == INT_MIN) ? INT_MAX : -n;
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
if (n < 1000000000) return 9;
return 10;
}
I've deleted the (in my opinion) unnecessary code. Everything else seems to work fine. The problem only happens with the large number on the first line. If related, i made a simple script in python to make the file equal.in
according to the rules, so the contents of the file are ok.