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

3
  • 1
    You have to manually allocate memory for the array inside the function using malloc(). Then you have to assign the numbers into the array and return the array. After you done with the array, you must free the memory with free() function. Apr 11, 2011 at 21:23
  • 4
    This is probably the best first question I've seen on SO.
    – nmichaels
    Apr 11, 2011 at 21:25
  • The function does not return an array. It prints the contents of one. Apr 11, 2011 at 21:27

9 Answers 9

7

For starters

If your main() has return type int, don't forget to return a value from it!

int main(void)
{
   /* code here */

   return 0;
}

Problem 1

By

d[k]=i;
k++;
printf("%d ", d[k]);

I think you meant

d[k]=i;
printf("%d ", d[k]);
k++;

otherwise you're printing the "next" array element each time, which will be one-past-the-end of the array on the last loop iteration.

Problem 2

int i,k=0,d[k];

You make an array d of size k where k is 0. I think you intended for the array to automatically resize when you write k++, but this is not the case. The array is created with zero elements, and then that's its size for all time.

Your next instinct may be to create the array big enough in the first place:

int d[b-a+1];

Unfortunately, this is most likely wrong, too. It relies on a feature called Variable Length Arrays (or "VLAs"); although a GCC compiler extension (and, incidentally, C99) does allow this (and it's not clear whether you have that extension enabled and/or are allowed to use it in your homework — I will assume for this answer that you do not / are not), the language itself does not allow an array with a dynamic size.

What do I mean by dynamic size?

I mean that the variables a and b depend on user input: they are not known at compile-time. In general, the size of an array must be known at compile-time.

Note: If you use this, your code may compile without error, and your program may even appear to run and work correctly. However, you'd be relying on what's called "Undefined Behaviour", and your code could stop running or even crash at any time, due to any number of random, unpredictable factors. Even if it looks like it's okay, it's invalid. Don't do it!

Solution

Fortunately, there is a way to allocate a block of memory with the right size for your elements, when you don't know the elements until your program runs. It's called "dynamic allocation", and it involves a function call:

int *d = malloc(sizeof(int) * (b-a+1));

You can use the same syntax (d[k]) to access "elements" in this "array" or block of memory, but you must later manually free the memory:

free(d);

Possible problem 3

Your assignment says to return an array from the function, but you're not doing this. Instead, you're just creating, filling and printing the array all within the same function (which seems a bit pointless).

You can't actually return an array either, but since you're dynamically allocating the space for it, you have a pointer to work with. It's my opinion that your teacher may have wanted you to return a pointer to this array.

If so, the finished code looks a bit like this:

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

int *exc(int a, int b)
{

  int i, k = 0;
  int *d = malloc(sizeof(int) * ((b-a)+1));

  for (i=a; i<=b; i++) {
     d[k]=i;
     k++;
  }

  return d;
}

int main(void)
{
 int a,b,i,*ar;

 printf("Give first integer: ");
 scanf("%d",&a);
 printf("Give second integer: ");
 scanf("%d",&b);

 ar = exc(a,b);

 for (i=0; i < (b-a+1); i++) {
    printf("%d ", ar[i]);
 }

 free(ar);

 system("pause");
 return 0;
}

Disclaimer: I'm rusty on C, so the finished code might have a few syntax bugs.

Hope this helps!

6
  • @DShook: I explained in full detail exactly what's going on, with an example. This is no different than what he'd read in a good C book. Apr 11, 2011 at 21:45
  • @Tomalak Reading from a book and figuring it out yourself is a long ways from posting the question and having someone do it for you though.
    – DShook
    Apr 11, 2011 at 21:48
  • 3
    @DShook: This is Stack Overflow, not after-school class. Everyone has their way of teaching, and this is mine. Some people learn best by example. We'll likely never agree on this issue. :) Apr 11, 2011 at 21:49
  • Also, from the quality of the question (especially for a first question), I rather trust that the OP will use my answer wisely. I would not have posted this answer for everyone. Apr 11, 2011 at 21:50
  • I agree with Tomalak, it is their loss if they dont (want to) learn from the examples. Apr 11, 2011 at 22:01
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).

5
  • 2
    No OP shouldn't. That's not standard C. I doubt OP is supposed to use GNU C extension in a homework assignment.
    – rlibby
    Apr 11, 2011 at 21:24
  • @rlibby: I assumed he was allowed because of his posted code. If he's not I don't want to do his homework for him.
    – GWW
    Apr 11, 2011 at 21:25
  • 1
    @rlibby: OP code is either C99 (no return in main) or some non-standard version of C. In C99, defining arrays with a variable size "works". If he's using some non-standard version of C, all bets are off.
    – pmg
    Apr 11, 2011 at 21:31
  • I'm a beginner in c programming and I still haven't been taught how to use malloc and realloc stuff. But thanks for your help anyway.
    – captain
    Apr 11, 2011 at 21:32
  • @pmg, apologies as VLAs are C99 (I think I convinced myself they weren't by avoiding them like the plague (and also because they aren't C89)). GWW, you're right that it's moot anyway because OP should malloc and return that.
    – rlibby
    Apr 11, 2011 at 23:02
2

The order of statements is not correct

  d[k]=i;                          // d[0] = 42;
  k++;                             // ...
  printf("%d ",d[k]);              // print d[1]
1
  • LOL, I just pointed out something I thought you might want to change. I'm happy you figured it out :)
    – pmg
    Apr 11, 2011 at 21:30
2

You need to allocate the memory for the array first, use malloc with the amount of integers you need to assign

Also, to be true to the problem statement, have the function return a pointer to the array so the main function can print it out instead of the exec function doing it directly.

0
2

Doing somebodys homework is always somewhat bad but obviously OP has no idea how to aproach this particular problem so here is a full example of dynamic memory allocation (overly commented).

#include <stdio.h>
#include <stdlib.h> /* required for malloc() and free() */

/* function that retuns a pointer to int type of data */
int *create_array(int a, int b)
{
    int *array;
    int array_size = b - a + 1; /* assuming that 'a' is always smaller than 'b' */
    int i;

    array = malloc( array_size * sizeof(int) ); /* allocate memory for the array */
    if(array == NULL) exit(EXIT_FAILURE); /* bail out if allocation fails */

    /* assign the values into array */
    for(i = 0; i < array_size; ++i)
        array[i] = a++;

    /* return a pointer to our allocated array */
    return array;
}

int main(void)
{
    int *array;
    int i, a = 42, b = 50;

    /* and now we can call the function to create the array */
    array = create_array(a, b);

    /* print results */
    for(i = 0; i < b - a + 1; ++i)
        printf("%d\n", array[i]);

    /* always remember to free the data after you are done with it */
    free(array); 

    return 0;
}
1
  • 1
    You allocate less memory than you write to
    – fdermishin
    Apr 11, 2011 at 21:43
1

You incorrectly declare d array in your code:

int d[k];

should be:

int d[b-a+1];

Edit::

Also, as others have posted, the statement order is wrong:

d[k]=i;
k++;
printf("%d ",d[k]);

should be:

d[k]=i;
printf("%d ",d[k]);
k++;

because otherwise you "lose" the first value when k==0.

3
  • VLAs are a compiler extension. For the OP, this may silently "work" but be a horrible invocation of UB that he isn't even aware of. The array should be dynamically allocated. Apr 11, 2011 at 21:28
  • 1
    VLAs? UB? What is this? I'm a beginner in c programming.
    – captain
    Apr 11, 2011 at 21:30
  • @captain: I was talking to pajton, who knows what they are. Please refer to my answer, where I explain in detail. Apr 11, 2011 at 21:46
0

You made an array of size zero and then started throwing data in without resizing the array. I'm a bit surprised that you aren't getting an error.

You're accessing data from memory outside the safety of defined data storage. It should be an error because the results are not defined. The data past the end of your array could be used for anything. And since your array is size zero, everything is past the end.

1
  • yeah, I guess I just figured compilers would have improved to catch this sort of thing.
    – Tom Cerul
    Apr 11, 2011 at 21:29
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.

-1

It happens because you allocate memory for d on the stack. If you move the declaration of it outside the function, everything shoud be ok.

3
  • It is only one of many problems. It is said in the task that you should return the array. But if you just return d, possibly the program will fail, because d points to the stack memory and after function returns, this memory will be freed. But in current version all values are printed inside the function, so it doesn't matter now.
    – fdermishin
    Apr 11, 2011 at 21:33
  • @user502144: Arrays cannot be returned by value at all. Apr 11, 2011 at 21:44
  • If I say that an array is returned, I mean that the pointer to the first element is returned. So, if the pointer to the stack is returned, bad things can happen.
    – fdermishin
    Apr 11, 2011 at 21:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.