char *p & char p[]

博客主要介绍了C语言中字符串的相关操作。在准备部分,说明了`char *p`和`char p[]`的含义及存储情况;在访问操作部分,介绍了指针访问字符串数组指定索引位置内容的方法,还提及结构数组中获取指定索引元素的操作与字符指针访问类似。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Preparation

  • char *p & char p[]
char *p = "hello_world!"

<=equivalent to=>

char p[] = "hello_world!"

‘p’ means a pointer to character string, located in the stack. However, the real charactors content of "hello_world!" were stored in the RO AREA where it’s not allowed to be overriden.

  • char p[20] = “hello_world!”

‘p’ represents that the array name of a charactor array, meawhile, that indicates that the stack address of the first element of a charactor array(&p[0])

p -->  'h'
       'e'
       'l'  
       'l'
       'o'
       '_'
       'w'
       'o'
       'r'
       'l'
       'd'
       '!'
       '\0'

Access Operation

char  str[20]  = "hello_world!";

char *p = str;    ( or char *p = &str[0];)
  • Pointer Access
    if we wanna get the content of the designated index position in the charactors array.
    p[index] <=> *(p+index)
    eg: str[1] == p[1] == *(p+1) == ‘e’

  • Mindset Within Structure Array
typedef struct _st{
char  *p;
...
struct _st  *next;
}MSDN_ST,  *MSDN_ST_PTR;

MSDN_ST  st[10] ;
MSDN_ST_PTR  pst = &st[0];

The same with above charactor pointer access operation. we could do as following if we wanna get the element of the designated index position in the structure array.

eg: st[2] <=> pst[2] <=> *(pst+2)

st[2].p = "hello_world!";
pst[2].p = "hello_world!";
(*(pst+2)).p = "hello_world!";
(MSDN_ST_PTR )(pst+2)->p = "hello_world!"; // Keep in mind do memory mallocation for pointer `p`  before assignment operation.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值