mdh said:
source of puzzlement. I can understand why.
I reluctantly ask this...knowing it does not work, but the issue is
why? ( It is related to exercise 5-13, K&R). I have looked at the FAQ,
but still no luck.
#include <stdio.h>
#include <string.h>
int main (int argc, const char * argv[]) {
int main( void )
would probably do in this case;-)
char *r[]={"abc","bcd","cde"};
What you define here is an array of three pointer, with each of them
initialized to point to a string literal. String literals are strings
that the compiler stows away somewhere in memory that you are not
allowed to write to, only to read from. (On some implementations
you actually can write to string literals, but that's not something
you should get in the habit of expecting.)
char s[]="uv";
char t[]="vw";
char u[]="wx";
Here you do something very different even though on a first glance it
may look similar. You define here three arrays, each with 3 elements
and the elements are initialized with the characters of the strings
on the right hand side. And each of these arrays consist of memory
that you can read from and write to as much as you like (and as long
as you don't try to read or write past the array boundaries;-).
And here you try to write to the memory where e the string literal
is stored that r[0] is pointing to. It looks like on your system
trying to write to that kind of memory is not possible at all. So
your program dies. If you would do it the other way round like in
char *r[] = {"uv","vw","wx"};
char s[] = "abc";
char t[] = "bcd";
char u[] = "cde";
strcpy(s, r[0]);
everything would be fine since now would be copying from the string
literal (i.e. only reading it) to memory you're allowed to write to.
My compiler gives a Sigbus 10 error...whatever that means
That often means that you try to write to a memory address that
is not properly aligned for the object you want to write to it.
E.g. on some machines an int must always be stored at an even
address (or even an address that's can be divided by four). If
you try to assign to write an int instead to an odd address
then you get a SIGBUS error. Often this is achieved by careless
programmers by using improper casts, like e.g.
char s[ 10 ];
char *p = s + 1;
int x = 3;
* ( int * ) p = x;
This may fail with a SIGBUS if 's' starts at an even address (but
there are also a lot of systems where it won't fail since they
have no such restriction). You should always use memcpy() if you
really have to do such things.
But on some systems you get a SIGBUS also if you try to write to
the memory of a string literal (I think on FreeBSD for all attempts
to write to read-only memory). On others you may get a SIGSEGV, i.e.
a segmentation fault (e.g. on Linux).
Regards, Jens