Reputation: 1
what is wrong with this?
why wont it work? its showing segmentation fault(core dumped)
Cant we use a[I]
?
#include<stdio.h>
int main()
{
int *a,i,n;
scanf("%d",&n);
*a=malloc(n*sizeof(int));
for(i=0;i<n;i++)
a[i]=i;
free(a);
return(0);
}
Upvotes: 0
Views: 71
Reputation: 6057
*a = malloc( n * sizeof(int) );
should be a = malloc ( n * sizeof(int) );
malloc()
allocates the storage and returns a pointer to the first byte.
As a
is pointer variable is should point to the address.
Where as *a
is incorrect in this case, because *
along with pointers is used for de-referencing.
Upvotes: 1
Reputation: 36438
Please enable compiler warnings; something should be screaming at you about:
*a=malloc(n*sizeof(int));
This says:
a
(which is uninitialized and points to no known location).a
itself is still pointing nowhere in particular.
Then:
a[i]=i;
writes into that random space.
You want to say:
a = malloc(n * sizeof(int));
Upvotes: 2
Reputation: 150108
You are setting the memory address pointed to by a
to the address returned by malloc. Since a
is not yet initialized, you are setting an undefined part of memory to the address returned by malloc.
*a=malloc(n*sizeof(int));
Instead, set the pointer itself
a=malloc(n*sizeof(int));
Upvotes: 0