char * 和 int * 的 C 指针算法不同 [英] C pointer arithmetic different for char * and int *
问题描述
有人可以解释为什么我可以使用以下代码移动 char * 而不是 int * 的内存位置:
Could someone explain why I can move through the memory locations for the char * but not for the int * using the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int * a = malloc(48);
char * s = malloc(27);
for (int i = 0;i<26;i++) s[i] = i+65;
int intSize = sizeof(int);
printf("%d\n",intSize);
for(int i = 0;i<12;i++){
a[i] = i;
printf("%d %d %c\n",*(a+i*intSize),a[i],*(s+i));
}
return 0;
}
推荐答案
当你声明一个变量时,例如
when you declare a variable e.g.
int* a;
char* b;
所有的偏移量最终都是按字节偏移量计算的,偏移量的大小取决于类型.
all offsets are in the end calculated as byte offsets, the size of the offset depends on the type.
so a + 1
实际上是 a + sizeof(int)
而 b + 1
实际上是 b + sizeof(字符)
so a + 1
is in reality a + sizeof(int)
and b + 1
is in reality b + sizeof(char)
编译器会处理这个问题,它使代码更容易阅读,否则在遍历数组等时,你总是需要计算一个类型有多少字节
the compiler handles this, it makes it easier to read the code otherwise you would always have to calculate how many bytes a type has when looping through an array and such
这篇关于char * 和 int * 的 C 指针算法不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!