2015年7月29日 星期三

C 筆記 char 用strlen

The array declaration char a[6]; requests that space for six characters be set aside, to be known by the name a. That is, there is a location named a at which six characters can sit. The pointer declaration char *p; on the other hand, requests a place which holds a pointer. The pointer is to be known by the name p, and can point to any char (or contiguous array of chars) anywhere.
The statements
 char a[] = "string";
 char *p = "string"; 
would result in data structures which could be represented like this:
     +---+---+---+---+---+---+----+
  a: | s | t | r | i | n | g | \0 |
     +---+---+---+---+---+---+----+
     +-----+     +---+---+---+---+---+---+---+ 
  p: |  *======>; | s | t | r | i | n | g |\0 |    
     +-----+     +---+---+---+---+---+---+---+ 
It is important to realize that a reference like x[3] generates different code depending on whether xis an array or a pointer. Given the declarations above, when the compiler sees the expression a[3], it emits code to start at the location a, move three elements past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location p, fetch the pointer value there, add three element sizes to the pointer, and finally fetch the character pointed to. In the example above, both a[3] and p[3] happen to be the character l, but the compiler gets there differently.

char *p = "string"; 
用strlen算長度,不要用sizeof
因為sizeof試算pointer長度


沒有留言:

張貼留言