> since s is effectively an array, or am I missing something?
s isn't an array, and yes you're missing quite a lot.
First off, you can't use s with impunity as some infinitely long array which the compiler looks after for you.
It's up to you to make sure that it is set to point to some allocated memory.
Let me say that again, if you have any pointers, it's
your responsibility to make sure they point somewhere. The compiler does nothing automatic for you.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *s;
int k;
} mystruct;
int main ( ) {
mystruct str1,str2;
str1.s = malloc(10);
strcpy( str1.s, "hello" );
str1.k = 22;
printf( "%s %d\n", str1.s, str1.k );
// This only copies the pointer
// changes to str2 will affect str1 and vice-versa
str2 = str1;
strcpy( str2.s, "HELLO" );
printf( "%s %d\n", str1.s, str1.k );
printf( "%s %d\n", str2.s, str2.k );
// now the killer blow
// since they're both the same pointer, freeing one
// also frees the other
// str2.s pointer now points nowhere valid - a particularly hard
// bug to find in a large program
free( str1.s );
return 0;
}
If on the other hand, you made s a proper array to start with, none of that would be a problem.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char s[10];
int k;
} mystruct;
int main ( ) {
mystruct str1,str2;
strcpy( str1.s, "hello" );
str1.k = 22;
printf( "%s %d\n", str1.s, str1.k );
str2 = str1;
strcpy( str2.s, "HELLO" );
printf( "%s %d\n", str1.s, str1.k );
printf( "%s %d\n", str2.s, str2.k );
return 0;
}
> Also, it looks to me like the declared dimension of s should be specified somewhere
Yes, in a call to malloc for example.
> s will be using a contiguous space
No - the compiler does nothing in terms of allocating memory to pointers. Like I said, its all up to you.
--