Alex Rivera | Logout

Return an array with all integers from a to b

Asked 2011-04-11T21:17:16.343
10

The exercise says "Create a function with two parameters a and b which are integers and the function will return an array of integers with every number from a to b.

#include <stdio.h>
#include <stdlib.h>

void exc(int a, int b){
  int i,k=0,d[k];
  for(i=a;i<=b;i++){
  d[k]=i;
  k++;
  printf("%d ",d[k]);
  }
}

int main(void){
 int c,d;
 printf("Give first integer: ");
 scanf("%d",&c);
 printf("Give second integer: ");
 scanf("%d",&d);
 exc(c,d);
 system("pause");
}

The problem is that if I put for example c=2 and d=5 the program returns something like 2088806975 16384 1 2293536 instead of 2 3 4 5. Where is the problem? Thanks

Edit
Report

2 Answers

3

The size of d is always 0. Since you are initializing it as d[k]. You should instead do something like d[b-a+1].

Update:

Furthermore, the order of your statements are wrong, see pmg's answer.

Update 2:

Your code doesn't actually return the array you are creating and it won't work unless you create the array on the heap (ie. using malloc / free).

answered 2011-04-11T21:19:24.903
0

There are a couple problems. First, d is not returned from exc. Of course, you shouldn't just return it since it's allocated on the stack. Secondly, the printf is called after you increment k. That prints the next element in d, not the one whose value you just filled in. Finally, d doesn't have any space allocated for it, since k is always 0 when d is created.

answered 2011-04-11T21:21:21.133

Your Answer