Well, I have been playing around to pass an array as a argument in a function and that function would loop through array and write its content but here is my probelm, i want that function to take a pointer to first element only as its param.
But my problem here I can't figure where does array end.
I saw that in string there is somthing like that but i cant figure how it works
If you're doing this with strings, you will need to terminate the end of your character array with the '\0' character. That can be done like so char data[] = {'2','3','4','6','6','6','\0'} ;
or char data[] = "234666";
The double-quotes will automatically terminate a string with the null character.
If it's not just char arrays that you need to pass, then you have a couple of options:
1. Pass the array size into the function as an argument:
1 2 3 4 5 6 7
int myarray[1000];
int size = 0;
while(someCondition)
myarray[size++] = someValue;
MyFunction(myarray, size);
2. Use the sizeof function to get the size. I've heard people suggest this, but have never got it to work properly.
1 2 3 4 5
MyFunction(int Input[])
{
int size = sizeof(Input) / sizeof(Input[0]);
//your code here
}
1 2
int myarray[] = {2,3,4,5,6,7,6,4};
MyFunction(myarray);
well I already know these stuff i just want to know how the standard library approaches that in the example above though the array isnt null terminated.
2. Use the sizeof function to get the size. I've heard people suggest this, but have never got it to work properly.
MyFunction(int Input[])
{
int size = sizeof(Input) / sizeof(Input[0]);
//your code here
}
If you have never got it to work properly (properly - is it how?!) why you suggest it?!
It works properly but not as you think. sizeof( Input ) in this code is equivalent to sizeof( int * ) and usually is equal to 4 on 32-bit system. So the result will be equal to 1 ( sizeof( int * ) / sizeof( int ) == 4 / 4 ).
@Damadger
But my problem here I can't figure where does array end.
You should pass to the function also the size of your array. For example
1 2 3
void SomeFunction( char a[], int size );
SomeFunction( data, sizeof( data ) / sizeof( *data ) );