Newsgroups: comp.lang.c Path: utzoo!telly!problem!druid!darcy From: darcy@druid.uucp (D'Arcy J.M. Cain) Subject: Re: confusion with char *a and char a[NUM] Organization: D'Arcy Cain Consulting, West Hill, Ontario Distribution: na Date: Tue, 4 Dec 90 04:33:51 GMT Message-ID: <1990Dec4.043351.9655@druid.uucp> References: <7656@umd5.umd.edu> In article <7656@umd5.umd.edu> jjk@astro.umd.edu( Jim Klavetter) writes: >I can have two identical files except that one I declare a to be > char a[NUM] >and the other has > char *a with a malloc of NUM+1 characters. > [...] >In both cases, the following is accepted by both my sun4 compiler and >gcc > strcpy(string, a) >and there is no problem. > >However, if I have > a=strchr(string, ":"); >I get the error message > 121: incompatible types in assignment >or some such thing (that one is from gcc). I know there are people better qualified to answer this but I'd like to attack this from a slightly different angle. Perhaps it will shed some light for those who haven't grasped the difference between pointers and arrays. #if A_IS_A_CONSTANT #define a 3 #else int a = 3; ... foo(a); When 'a' is a constant the value is passed to foo. If it is a variable then the CPU must get the value from memory and then use the resulting value. Note that in both cases foo gets exactly the same thing as an argument (the value 3.) There is no such thing as a 'constant' or 'variable' argument to a function. Think of an array as a constant. if you declare char a[NUM]; then a is a constant unchanging value. It is almost like saying: #define a ADDRESS_OF_A_SPECIFIC_MEMORY_LOCATION and when you pass this as an argument you pass the value of the specific memory location. If, on the other hand you declare char *a = ADDRESS_OF_A_SPECIFIC_MEMORY_LOCATION; then you have created a variable and initialized it to a specific location. The difference here is that the value stored at 'a' can be modified, for example by assigning the return value from malloc. However when you call a function with this as an argument, the value is read from memory and that value is sent to the function. The called function gets exactly the same kind of value in both cases. As to why your example doesn't work, you are in effect trying to assign a returned address (from strchr()) to a constant (the array address 'a'.) This is somewhat like saying 3 = getchar(); I know that I have played fast and loose with some concepts but I think that this may help some people. I strongly suggest rereading the FAQ if you think the above helped to drop the penny. -- D'Arcy J.M. Cain (darcy@druid) | D'Arcy Cain Consulting | There's no government West Hill, Ontario, Canada | like no government! + 416 281 6094 | Brought to you by Super Global Mega Corp .com