Ankit Kathuria
Ankit Kathuria

Reputation: 1

Accessing Arrays created Using Malloc

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

Answers (3)

ani627
ani627

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

Paul Roub
Paul Roub

Reputation: 36438

Please enable compiler warnings; something should be screaming at you about:

*a=malloc(n*sizeof(int));

This says:

  1. Allocate some memory.
  2. Assign that address to the integer pointed to by 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

Eric J.
Eric J.

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

Related Questions