Reputation: 23
I'm having this issue while trying to solve this question on HackerRank. On repl.it my code goes well, but on their console i have this problem.
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t; //qtd de viagens
int m; //dinheiro para os sorvetes
int n; //qtd de sabores de sorvetes
int c[n+1]; //preço de cada sorvete
int r[t];
int s[t];
scanf("%d", &t);
for(int j = 0; j < t; j++){
scanf("%d", &m);
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%d", &c[i]);
}
for (int i = 1; i < n; i++){
for(int k =i+1; k <= n; k++){
if (c[i]+c[k] == m){
r[j] = i;
s[j] = k;
}
}
}
}
for(int i = 0; i < t; i++){
printf("%d %d\n", *&r[i], *&s[i]);
}
return 0;
}
Input:
2
4
5
1 4 5 3 2
4
4
2 2 4 3
Output on repl.it:
1 4
1 2
Output on HackerRank:
~ no response on stdout ~
It also gives me a Segmentation Fault message.
Upvotes: 2
Views: 21025
Reputation: 821
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t, m, n;
//Declaration of dynamic arrays "r", "s" and "c"
int *c, *r, *s;
scanf("%d", &t);
//Allocation of memory for the int arrays "r" and "s"
r = malloc(t * sizeof(int));
s = malloc(t * sizeof(int));
for(int j=0; j < t; j++){
scanf("%d", &m);
scanf("%d", &n);
//Allocation of memory for the int array "c"
c = malloc(n+1 * sizeof(int));
for(int i = 1; i <= n; i++){
scanf("%d", &c[i]);
}
for (int i = 1; i < n; i++){
for(int k = i+1; k <= n; k++){
if ((c[i] + c[k]) == m){
r[j] = i;
s[j] = k;
}
}
}
free(c);
}
for(int i = 0; i < t; i++){
printf("%d %d\n", *&r[i], *&s[i]);
}
free(r);
free(s);
return 0;
}
I use valgrind to detect memory leaks:
==53541== HEAP SUMMARY:
==53541== in use at exit: 0 bytes in 0 blocks
==53541== total heap usage: 6 allocs, 6 frees, 2,081 bytes allocated
==53541==
==53541== All heap blocks were freed -- no leaks are possible
Upvotes: 1
Reputation: 280
You have 2 problems here:
You are using VLA and its not supported by all compilers.
I'm talking about that:
int c[n+1]
for example. Chage that to dynamic allocation
Initiallize variables with values before you use them (like you did with n
and t
).
Upvotes: 2