- is following code correct?
Yes, array a[] will be allocated on stack and a[0] just modifies the first character.foo() { char a[]= "I HATE U!"; a[0] = 'U'; }
- is following code correct?
Compiler won't complain, but the program will crash. The reason is "I HATE U!" is a constant that will be allocated in the constant memory region. If we try to modify its value thru pointer a, you will be hit by seg fault.foo() { char *a = "I HATE U!"; a[0] = 'U'; }
However, initializing the variable takes a huge performance and space penalty for the array (using char a[] = "XXXX"). Only use the array method if you intend on changing the string, it takes up space in the stack and adds some serious overhead every time you enter the variable's scope. Use the pointer method otherwise.
- is following code correct?
No, compiler will complain. a is a pointer points to char constant, you can modify what a points to (a's value), but you can't modify the content of the address that a points to (*a's value).foo() { cont char *a = "I HATE U!"; a[0] = 'U'; }
- is following code correct?
No, compiler will complain. a is a constant pointer, therefore you can'y modify what a points to (a's value). But you can modify the content of the address that a points to (*a's value) if that address is valid to access. In the above example, the address is not valid to access.foo() { char * const a = "I HATE U!"; a++; }
- is following code correct?
No, compiler will complain. char const *a is the same as const char * a.foo() { char const *a = "I HATE U!"; a[0] = 'U'; }
No comments:
Post a Comment