c语言数组偏移量,C如何为数组字符串获取数组偏移量?

它的工作方式与任何其他数据类型相同. “字符串”数组实际上是一个字符指针数组,它们都具有相同的大小.因此,为了获得指针的正确地址,它将索引乘以单个元素的大小,然后将其添加到基址.

你的数组将如下所示:

+---------+

fmts: | fmts[0] | ------+

+---------+ |

| fmts[1] | ------|--------------------------+

+---------+ | |

V V

this one is a little long\0this one is short\0

字符串本身的字符不存储在数组中,它们存在于其他地方.你拥有它的方式,它们通常存储在只读存储器中,尽管你也可以将它们malloc,甚至可以将它们定义为可修改的字符数组,例如:

char f0[] = "you can modify me without invoking undefined behaviour";

您可以使用以下代码查看此操作:

#include

const char *fmts[] = {

"This one is a little long",

"Shorter",

"Urk!"

};

int main (void) {

printf ("Address of fmts[0] is %p\n", (void*)(&(fmts[0])));

printf ("Address of fmts[1] is %p\n", (void*)(&(fmts[1])));

printf ("Address of fmts[2] is %p\n", (void*)(&(fmts[2])));

printf ("\n");

printf ("Content of fmts[0] (%p) is %c%c%c...\n",

(void*)(fmts[0]), *(fmts[0]+0), *(fmts[0]+1), *(fmts[0]+2));

printf ("Content of fmts[1] (%p) is %c%c%c...\n",

(void*)(fmts[1]), *(fmts[1]+0), *(fmts[1]+1), *(fmts[1]+2));

printf ("Content of fmts[2] (%p) is %c%c%c...\n",

(void*)(fmts[2]), *(fmts[2]+0), *(fmts[2]+1), *(fmts[2]+2));

return 0;

}

哪个输出:

Address of fmts[0] is 0x40200c

Address of fmts[1] is 0x402010

Address of fmts[2] is 0x402014

Content of fmts[0] (0x4020a0) is Thi...

Content of fmts[1] (0x4020ba) is Sho...

Content of fmts[2] (0x4020c2) is Urk...

在这里你可以看到数组元素的实际地址是等距的 – 0x40200c 4 = 0x402010,0x402010 4 = 0x402014.

但是,值不是,因为它们指的是不同大小的字符串.这些字符串位于单个内存块中(在这种情况下 – 无论如何都没有必要),如下所示,*字符表示单个字符串的开头和结尾:

| +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f +0123456789abcdef

---------+-------------------------------------------------------------------

0x04020a0| *54 68 69 73 20 6f 6e 65 20 69 73 20 61 20 6c 69 This one is a li

0x04020b0| 74 74 6c 65 20 6c 6f 6e 67 00*53 68 6f 72 74 65 ttle long.Shorte

0x04020c0| 72 00*55 72 6b 21 00* r.Urk!.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值