954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Array question

Hello.,
Have a question about array being set from function argument. I wrote this little program, and want to know why cant i set an array size from the function argument. Any help would be greatly appreciated.

int money(int deposit, ...){
  int 
      i,
      sum = 0,
      nextvar;
      // myArr[deposit]; // < -- in here i cant set the array size from function receiving argument? and why?
  va_list 
      parg;
  va_start(parg, deposit);
  for(i=0;i<deposit;i++){
    nextvar=va_arg(parg, int);
   // myArr[i]=nextvar;
    sum+=nextvar;
  }
  va_end(parg);
  return sum/deposit;
}
int main(void){
  printf("%d", money(4,4,4,4,4));
  getchar();
  return 0;
}

---
Andre Granovsky

atman
Junior Poster in Training
50 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

short answer: static arrays are allocated when the function is called, at which point your variable is undefined. so the construct is illegal.

if you want to dynamically allocate arrays, you need to use malloc() along with a corresponding free()

jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
 

>short answer: static arrays are allocated when the function is called...
Short remark: static arrays are allocated before the first call of the function. However no static arrays in OP snippet. Please, be more thoroughs in terms using.

ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

uh, yeah, i meant to say that the memory is allocated when the "program" is called.

but look if you want to be a pedant, then it's true there's no static array in the OP's snippet. what there is is an illegal attempt to use an undefined variable in what would otherwise have been a static array.

jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
 

>...if you want to be a pedant...
To make distinctions between static, automatic and dynamic attributes - is it too pedantic for you?
;)

ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

>static arrays are ............
You meant to say "fixed-length" arrays, right?

OP>in here i cant set the array size from function receiving argument? and why?
Because, array size should be a compile time constant, that is: the array size should be known at the compile time. You are already been told what is the solution by Dave.

siddhant3s
Practically a Posting Shark
816 posts since Oct 2007
Reputation Points: 1,486
Solved Threads: 140
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You