I'm trying to write a program which starts by creating a 2D array that will represent a graph (note that the dimensions of the graph will be given as input).
I want to initialize this array at 0 and after googling it I found out that you have to do it with memset(), cause the memory for the array will be dynamically allocated from the input file.
Below is a small part of my program so far:
long int N;
int main(int argc, char *argv[]) {
long int i;
FILE * txt;
txt = fopen(argv[1], "r");
if (txt == NULL) {
printf("There was an error trying to open the file.\n");
return 0;
}
fscanf(txt, "%li", &N);
long int graph[N][N];
memset(graph, 0, N*N*sizeof(long int));
return 1;
}
When I'm compiling it with gcc -Wconversion i'm getting the following warning:
warning: conversion to ‘long unsigned int’ from ‘long int’ may change the sign of the result [-Wsign-conversion] memset(graph, 0, N*N *sizeof(long int));
I can't understand at which point of the code the compiler is trying to convert a long int to an unsigned one. I searched it and people had the same problem only when they had variables of different types mixed.
Any help would be appreciated!
---EDIT---
With the help of 'Vlad from Moscow' I was able to solve the above warning (I had to change N to size_t type in order to call memset() correctly), but now I want to initialize another long int array to LONG_MAX and I get a different one:
memset(dist, LONG_MAX, N*sizeof(long int));
warning: overflow in implicit constant conversion [-Woverflow]
The function memset
expects the third argument of the type size_t
.
So declare the variable N as
size_t N;
and write
fscanf(txt, "%zu", &N);
The second warning is related to the second argument of the call of memset
memset(dist, LONG_MAX, N*sizeof(long int));
that expects it of the type int
that is internally within the function is converted to the type unsigned char
.
Here is the function declaration.
void *memset(void *s, int c, size_t n);
Usually the only applying of the function is to zero-initialize an array.