Thread: Stacks
View Single Post
  #2 (permalink)  
Old March 20th, 2004, 03:24 PM
davekw7x davekw7x is offline
Authorized User
 
Join Date: Feb 2004
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
Default

In a word: no.

(If this was a true/false question, and all that anyone wants to know is
the answer, that person can stop reading now.)

In a few more words:

Usually I would recommend that people with questions like this should
write a program that calls this function and see happens. Since you say
that you are just getting started, I'll write a program that does
something like yours, and suggest that you compile and run it and see
what happens.

This is a pretty useless routine for printing stuff, but is a good think-piece
to illustrate two points:

1. What is sizeof ?

2. How do functions process arrays that are passed as arguments.

sizeof is an operator, and C evaluates expressions with sizeof at
compile time.

The following illustrates the points, I think. I used a slightly
different function than you wrote, because it illustrates the point a
little better, I think.

In main(), C knows that stack was declared as an array of five doubles,
so sizeof(stack) is equal to the number of bytes allocated to that
array.

In print(), C only knows that stack is a pointer to a double (arguments
of type double x[] are treated as double *x, when being compiled by
C). Inside the function print(), sizeof(stack) is the number of bytes
required by a pointer to a double. There is no way, (I repeat no
way
) that print() can know the number of elements in the array unless
you tell it!

Try the program and see if it makes any sense.

Code:
#include <stdio.h>

#define STACK_SIZE 5
double stack[STACK_SIZE]; // initialise the array

int main()
{
  int i;
  void print(double stack[]);

  printf("\n\n");
  printf("Debug: In main():    sizeof(stack) = %d\n", 
          sizeof(stack));
  printf("Debug: Number of elements in stack =  %d\n\n", 
          sizeof(stack)/sizeof(stack[0]));

  for (i = 0; i < STACK_SIZE; i++) {
    stack[i] = 2 * i + 1;
  }
  print(stack);

  printf("\n\n");

  return 0;
}

void print(double stack[])
{
 int count;
 
    printf("Debug: In print(): sizeof(stack)   =  %d\n\n", sizeof(stack));
    for (count = 0; count < sizeof(stack); count++)
    {
       printf("%lf ", stack[count]);
    }
}
Regards,

Dave
Reply With Quote