Reputation: 23
I've been working on this simple coding challenge at HackerRank. I decided to implement my solution as a C function because any doing it in another language or in the main function itself seemed trivial. I assumed that I'd muck up the array/pointer syntax a few times doing it this way and I'd have a chance to learn something.
This is my function :
int sum_diagonal(int n, int (*arr)[n]) {
int lD, rD, sum;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if (i == j) {
rD += arr[i][j];
}
if ((i+j) == (n-1)) {
lD += arr[i][j];
}
}
}
sum = abs(lD - rD);
return sum;
}
And this is the main()
function that calls it (the code to input the matrix was provided) :
int main(){
int n;
scanf("%d",&n);
int a[n][n];
for(int a_i = 0; a_i < n; a_i++){
for(int a_j = 0; a_j < n; a_j++){
scanf("%d", &a[a_i][a_j]);
}
}
//printf("why does this make it work?");
int sum = sum_diagonal(n,a);
printf("%d", sum);
return 0;
}
Sometimes it works exactly as intended, and sometimes I get garbage output. Stranger still, though, is the fact that if I uncomment that random printf()
call in the main function it seems to work every time. What is going on?
Upvotes: 2
Views: 122
Reputation: 325
You are trying to use a non-constant value (n) to setup the size of your array. Thats not working in C. If you need a flexible size of your array, you should use malloc() to allocate memory.
int n;
scanf("%d",&n);
int a[n][n]; //n is a non-constant value.
Otherwise you could use a fix size of your array by using #define for example:
#define SIZE_OF_ARRAY 5
int a[SIZE_OF_ARRAY ][SIZE_OF_ARRAY ];
Upvotes: -1
Reputation: 134346
In your code, you have defined
int lD, rD, sum;
without initializing and then, you wrote
rD += arr[i][j];
and
lD += arr[i][j];
rD
and lD
are automatic local variable and are not initialized. In the very first iteration itself, you're using them as to read the values from them (i.e., LHS of +=
).
At that point of time, their content (values) are indeterminate. Using them, as you've done, invokes undefined behavior.
Solution: Initialize your local variables always, like
int lD = 0, rD = 0, sum= 0;
Upvotes: 6