-1

Possible Duplicate:
C sizeof a passed array
Why sizeof(param_array) is the size of pointer?

I'm new to C, and am a little confused by the type system. I'm trying to write some code to print the number of lower case characters in a string, but only an int-sized piece of my array gets passed to the cntlower function. Why is this?

#include "lecture2.h"

int main(void){
    int lowerAns;
    char toCount[] = "sdipjsdfzmzp";
    printf("toCount size %i\n", sizeof(toCount));
    lowerAns = cntlower(toCount);
    printf("answer %i\n", lowerAns);
}

int cntlower(char str[]) {

    int lowers = 0;
    int i = 0;
    printf("str size %i\n", sizeof(str));
    printf("char size %i\n", sizeof(char));

    for(i = 0; i < (sizeof(str)/sizeof(char)); i++) {
         if(str[i] >= 'a' && str[i] <= 'z') {
               lowers++;
         }
    }

    return lowers;

}

As it is, the output is currently: toCount size 13 str size 4 char size 1 answer 4

I'm sure the reason for this is obvious for some of you, but unfortunately it isn't for me!

Community
  • 1
  • 1
user1804523
  • 53
  • 1
  • 1
  • 4
  • Read http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array for similar examples on what you're doing wrong with sizeof and pointers. – rutgersmike Nov 06 '12 at 22:24

1 Answers1

2

A char str[] argument to a function is actually syntactic sugar for a char*, so sizeof(str) == sizeof(char*). That happens to coincide with sizeof(int) on your platform.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836