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

int foo(char str[])
{
    char *str1=(char *)malloc(sizeof(char )*sizeof(str));

    printf("\n str %s  size : %zu  \n",str,sizeof(str));    
}

int main()
{
    char str[]="879879879-=-=-@#$@#$abcd";
    printf("\n str %s  size : %zu  \n",str,sizeof(str));

    foo(str);
    return 0;
}

Why is string length different in main() and foo()? This is a simple program in which main calls foo with str — the same str which is showing length 25 in main and in foo 8: why?

Output:

str 879879879-=-=-@#$@#$abcd  size : 25  
str 879879879-=-=-@#$@#$abcd  size : 8 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    In the function, `char str[]` is equivalent to `char *str` and the size of a pointer is smaller than the size of the specific string you're playing with. In the main function, `str` is an array and `sizeof` reports on the size of the array, including the terminal null byte, which means `sizeof(str) == strlen(str) + 1` — inside `main()`. (Note that you leak memory in `foo()`.) – Jonathan Leffler Jan 18 '17 at 00:24
  • might be helpful: http://www.c-faq.com/aryptr/index.html – yano Jan 18 '17 at 00:27

1 Answers1

3

In this function declaration

int foo(char str[]);

the parameter declared like an array is adjusted to pointer of type char *.

Thus these function declarations

int foo(char str[1000]);
int foo(char str[100]);
int foo(char str[1]);
int foo(char str[]);

declare the same one function and equivalent to

int foo(char *str);

As result within the function this expression

sizeof(str)

yields the size of a pointer of the type char *.

Within the main where there is indeed declared an array

char str[]="879879879-=-=-@#$@#$abcd";

this expression

sizeof(str)

yields the size of the array.

If you want to allocate memory in the function to store the string that is kept in the array then instead of the operator sizeof you should use standard string function strlen. For example

int foo(char str[])
{
    char *str1 = (char *)malloc( strlen( str ) + 1 );
    strcpy( str1, str );

    // ...
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335