> No, that wouldn't work because you're trying to assign a char*
> to a char. Remember that just the name of the array with
> nothing else is a pointer to the first element, essentially it's
> saying array[0]. It's already dereferenced, so you're looking at
> the value, not the address
No. You are wrong. Well actually, you're right and wrong at the
same time.
It is legal to do the following:
Code:
char* myfun( char *s ) //duplicate a string
{
//this code is irrelevent.
//pay attention to the actual use of the function
char *d = NULL;
if ( s == NULL ) return NULL;
d = malloc ( strlen( s ) + 1 );
strncpy( d, s, strlen(s) );
return d;
}
int main ( void )
{
char array[SIZE];
char *s;
//valid
s = myfun( "hello" );
puts( s );
free( s );
//valid
strncpy( array, "hi", 2 );
s = myfun( array );
puts( s );
free( s );
//valid, assuming 's' is pointint to usable space
//note, this would actually cause a memory leak
//because 's' isn't being freed inside the function,
//so it'd end up pointing to the new string, "losing"
//the old string. however, it is still legal
s = myfun( s );
//invalid.
//actually, it _is_ valid. You could do this. It however,
//is wrong. since 'array' is an array, even though it
//is treated as a pointer, it is wrong in this case because
//we're actually telling it to point some place else. this
//is the reason it is wrong.
array = myfun( s );
The reason assigning a value to array is incorrect in this place is because we're trying to assign 'array' a new value, rather than use it's currently allocated memory block.
With an array, you cannot just use 'realloc' or something to give it new space. This is the only real way they differ.
Quzah.