Reputation: 11
I have used the below code for a simple operation (to reverse a string). But the program is not executing. It gets a run time error (SIGSEGV) . I used a GCC compiler. Please help me in debugging the program.
#include <stdio.h>
#include <stdlib.h>
int *create(int n) {
int *a;
a = (int *)malloc(n * sizeof(int));
return a;
}
void get(int *a, int n) {
int i;
for (i = 0; i < n; i++) {
scanf("%d", *(a + i));
}
}
void reverse(int *a, int n) {
int i;
for (i = n - 1; i >= 0; i--) {
printf("\n %d", *(a + i));
}
}
int main() {
int n, *a;
scanf("%d", &n);
a = create(n);
get(a, n);
reverse(a, n);
return 0;
}
Upvotes: 1
Views: 32
Reputation: 75062
scanf("%d",*(a+i));
invokes undefined behavior because you passed int
where int*
is expected.
You must pass pointer to tell scanf()
where to store the data read, so stop dereferencing and try using scanf("%d",(a+i));
instead.
More notes are:
malloc()
in C.Upvotes: 1