Custom Search

Thursday, March 15, 2007

C - Review II 12 - 14

12. main(){

char *p = “hello world”;

p[0]='H';

printf(“%s”,p);

}

Output: segmentation fault

hello world is treated as constant string. If we want to modify the string allocate it as

char p[20]=”hello world”;

13. struct list {

char *item;
struct list *next;
}
/* Here is the main program. */
main(int argc, char **argv)
{ ... }
This program compiled correctly but giving runtime error “Core dumped”. Why?
Because main assumes that it is returning a structure. Observe there is no semi-colon after the structure declaration. (The connection is hard to see because of the intervening comment.) Since structure-valued functions are usually implemented by adding a hidden return pointer , the generated code for main() tries to accept three arguments, although only two are passed (in this case, by the C start-up code)

14. struct record {

char *name;
int refcount : 4;
unsigned dirty : 1;
};
What is special in this structure?
The colon represents number of bits to be allocated for the varaible. In this case refcount will be allocated only 4 bits instead of 32 bits(4 bytes). It is very useful, when we want to save memory.

No comments: