Passing Array to function

Hi
In my sample code :
1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

void Print_My_String (const char My_String[0])
{
        printf ("%s\n",My_String);
}
void main ()
{
Print_My_String("Test 1 2 3 4");
}


Despite defining MyString as array with 0 index,Print_My_String function prints my passed string "Test 1 2 3 4" without any error.
In fact determining index number in My_string array is meaningless.
I want to limit size of passed array to my function but with this method I could not do it.

The code you demonstarted shall not be compiled because you may not specify the size of an array as zero. So I wonder if the code indeed was compiled by your compiler. In my opinion it is a compiler bug.

If you want to use a sub array you should declare two parameters: the initial address of the sub array and its size. For example (I think your program is written in C)

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

void Print_My_String ( const char *My_String, size_t n )
{
        printf ("%*.*s\n", n, n, My_String);
}

int main( void )
{
        Print_My_String( "Test 1 2 3 4" + 5, 1 );
}
Hi
Thanks for your quick reply.
But my code has been compiled with gcc on linux!!
I am sure that it is a compiler bug. Though these function declarations are equivalent

void f( const char *s );
void f( const char s[] );
void f( const char s[10] );
void f( const char s[100] );

and decllare the same function because an array is implicitly converted to a pointer to its first element nevertheless you may not declare an array with zero size. And specifying a parameter in a function declaration is in turn a declaration.
Last edited on
By the way the compiler shall issue at least a warning because you incorrectly defined function main. It shall be defined as having return type int.
Topic archived. No new replies allowed.