Hi,
i have some troubles with a code like this:
void main (void)
The standard specifies two ways of defining main(); you can use any
other method that is equivalent to one of the two standard ways. Both
methods return an 'int'. Declaring 'int' to return anything other than
'int' means that a C compiler is not required to accept your code.
{
char array[2];
function1(array);
At this point, there's no declaration in scope for function1(). In C90,
it would be implicitly declared as returning 'int' and taking a fixed
but unspecified number of parameter of unspecified types; this was a bad
idea, because it's very error prone, which is why it's no longer allowed
in C99.
You should provide a function prototype. The simplest way, and the one I
prefer, is to define function1() before defining main() - the first part
of the function definition qualifies as a function prototype prototype.
Other people find it confusing to declare functions before calling them,
in which case just write a prototype that is not a definition:
void function(char *);
}
void function1(char * data)
{
....
function2(data)
There's a missing ';'.
}
function2(char * func2data)
You didn't declare a return type for function2, which is another
indication that you're writing for C90. In C99 and later, such
declarations are no longer allowed. I recommend providing a function
prototype.
{
...
}
I know that function2 works well, but in this case array memory address seems lost: the array memory address before funtion1 is different from its address after function1
I'm not sure why you think the address has changed; if you could provide
the evidence you used to reach that conclusion, we can probably explain
to you why that evidence doesn't mean what you thought it meant.
Here's a minor re-write of your code:
#include <stdio.h>
static void function2(char * func2data)
{
printf("funcdata:%p &funcdata:%p\n",
(void*)func2data, (void*)&func2data);
}
static void function1(char * data)
{
printf("data:%p &data:%p\n", (void*)data, (void*)&data);
function2(data);
}
int main (void)
{
char array[2];
function1(array);
printf("array:%p &array:%p\n", (void*)array, (void*)&array);
return 0;
}
Here's the results I got:
data:0xbf95577e &data:0xbf955760
funcdata:0xbf95577e &funcdata:0xbf955740
array:0xbf95577e &array:0xbf95577e
All of the pointers that should be equal printed out the same; all of
the pointers that should be different printed out differently, so that
output matches my understanding. If anything about it seems odd, let us
know, and someone will be able to explain it to you.