3

I'm trying to get data from std stored into an array, using pointers. The main declares d as int *d; and the function is called using x = getdata(&d); When I step through it with gdb it dies at the first iteration of the for loop, when it tries *d[i]=val;

int getdata(int **d)
{ 
    int count,val,i,j=0; 

    scanf("%d", &count);

    d = malloc(sizeof *d * count);
    for( i = 0; i < count-1; i++) {

    scanf("%d",val);

    *d[i]=val;  

    }

    for ( i = 0; i < count; i++)
            printf("Number %d\n",*d[i]);

    return count;

}

3
  • Say *d = malloc(sizeof **d * count);, and (*d)[i]. Commented Jan 18, 2013 at 0:25
  • Maybe he wants (*d)[i] ? Commented Jan 18, 2013 at 0:31
  • 1
    scanf("%d", &val); BTW: a serious compiler should warn you about this. Commented Jan 18, 2013 at 0:39

3 Answers 3

2

The memory should be allocated as follows

*d = malloc(count * sizeof **d);

The values should be accessed as follows

(*d)[i] = val;

It is also not clear why you allocate count elements and only initialize count - 1 elements in the input cycle (and later print all count elements in output cycle).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it was this and me forgetting the & in scanf("%d",&val) !
2
*d = malloc(count * sizeof(int));

then

(*d)[i] = val

Comments

2

What you have is a pointer to an array, not an array of pointers.

1) malloc returns a void* so you need to assign the result to *d instead of d

2) the data size you want is of an int, not an int* (using *d gets you an int* where **d is an int)

*d = malloc(sizeof(**d) * count);

3) Indexing the array requires slightly different syntax

(*d)[i] = val;

printf("%d\n", (*d)[i]);

4) The second scanf needs a pointer, not an int

scanf("%d", &val);

5 Comments

*d = malloc(count * sizeof **d ); is more robust than sizeof type .
I agree with this. Edited
you don't need the parentheses with sizeof expression (that's why I put "count" in front)
I'm still getting a segmentation fault
I missed the &val on your second scanf.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.