Are char * str & char str[] same ?

Lets have look at one of the bothering subject of 'C' to newbie programmers. Yes , You guessed it right it is POINTERS. nightmare of Computer science students.
(Here is interesting(for me at least ) discussion on Pointer's evilness)


First lets see basic definition of pointer -

pointer is a variable which contains the address in memory of another variable

Let's visualise memory location and pointer as above. You can see MemAd007 is valid memory location having some data value. Now there is another memory location labeled as pointer and having value as MemAd007 .
What is difference between pointer & MemAd007 memory location ?
Answer is pointer contain memory address and other data( its can be int, float...any data)
Lets consider sample code in C


1
2
3
4
5
6
7
8
#include<stdio.h>

int main(){

   char * str ="hello";
   char  s[10]="hi" ;
   return 0;
}

Now time for making hands dirty with assembly code ....
You can get assembly code from c using
#>gcc -O2 -S -c <program_name>
But instead I found website where we can get more informative assembly code from C.
Below is assembly code for above program. (You can use this tool to do it online - http://assembly.ynh.io/)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
              .Ltext0:
               .section .rodata
              .LC0:
0000 68656C6C   .string "hello"
     6F00
               .text
               .globl main
              main:
              .LFB0:
               .cfi_startproc
0000 55         pushq %rbp
               .cfi_def_cfa_offset 16
               .cfi_offset 6, -16
0001 4889E5     movq %rsp, %rbp
               .cfi_def_cfa_register 6
0004 4883EC30   subq $48, %rsp
0008 64488B04   movq %fs:40, %rax
     25280000 
     00
0011 488945F8   movq %rax, -8(%rbp)
0015 31C0       xorl %eax, %eax
0017 48C745D8   movq $.LC0, -40(%rbp)
     00000000 
001f 48C745E0   movq $26984, -32(%rbp)
     68690000 
0027 66C745E8   movw $0, -24(%rbp)
     0000
002d B8000000   movl $0, %eax
     00
0032 488B55F8   movq -8(%rbp), %rdx
0036 64483314   xorq %fs:40, %rdx
     25280000 
     00
003f 7405       je .L3
0041 E8000000   call __stack_chk_fail
     00
              .L3:
0046 C9         leave
               .cfi_def_cfa 7, 8
0047 C3         ret
               .cfi_endproc
              .LFE0:
              .Letext0:

You can see here there is section called .rodata which stores value "hello" as it is. You can read more about this data section @ http://www.bravegnu.org/gnu-eprog/c-startup.html.
So its clear that s, and str are stored differently in memory itself. As "hello" stored in .rodata section, which is read only section hence we can not modify contents of 'str' but we can modify contents of 's' easily.
Hope this small experiment clears you doubt.