c 程序 - 为什么整数占用 4 个字节,却以 8h 为间隔存储

标签 c memory int

有人可以向我解释一下为什么使用 scanf() 从用户处获取的 int 存储在 8h 的地址中吗?即使我的 64 位机器上的 int 大小为 4 个字节?它与内存中的对齐有关吗?

#include <stdio.h>
void main() {

    int *a;
    int i, n;



    printf(" Input the number of elements to store in the array : ");
    scanf("%d",&n);

    printf(" Input %d number of elements in the array : \n",n);

    printf("size of on int is %d\n", sizeof(i));

    for(i=0;i<n;i++) {
        printf(" element - %d : ",i+1);
        printf("address of a is %p\n", &a+i);
        scanf("%d",a+i);
    }

   return 0;

}


 Input the number of elements to store in the array : 3
 Input 3 number of elements in the array : 
size of on int is 4
 element - 1 : address of a is 0x7ffda5cf8750
6
 element - 2 : address of a is 0x7ffda5cf8758
5
 element - 3 : address of a is 0x7ffda5cf8760
2

最佳答案

#include <stdio.h>
void main() {

    int *a;
    int i, n;

下面有没有漏掉的代码?如果不是,a 现在是一个具有不确定值的未初始​​化指针。

    printf("address of a is %p\n", &a+i);

在这里,您使用 & 运算符获取a地址。结果是一个指向a的指针,IOW 是一个指向指针的指针。 64 位系统上指针的大小是 8,所以这应该可以回答您的问题。

    scanf("%d",a+i);

在这里,您写入一些“随机”内存位置。这是未定义的行为

<小时/>

供您引用,您似乎想做的固定程序:

#include <stdio.h>
#include <stdlib.h> // <- needed for malloc()/free()

// use a standard prototype, void main() is not standard:
int main(void) {

    int *a;
    int i, n;

    printf(" Input the number of elements to store in the array : ");
    if (scanf("%d",&n) != 1)
    {
        // check for errors!
        return 1;
    }

    // allocate memory:
    a = malloc(n * sizeof(int));

    for(i=0;i<n;i++) {
        printf(" element - %d : ",i+1);
        if (scanf("%d", a+i) != 1)
        {
            // again, check for errors!
            return 1;
        }
    }

    // [...]

    // when done, free memory:
    free(a);

    return 0;
}

要了解如何更稳健地进行输入,请阅读有关 scanf()fgets()strtol() 的文档.. .我准备了a little document ,但是网上还有很多其他资源,例如this FAQ on SO .

关于c 程序 - 为什么整数占用 4 个字节,却以 8h 为间隔存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44546962/

相关文章:

c - 如何解析来自基于 C 的 Web 服务器的 HTTP 请求

使用较小内存量时出现 C++ std::bad_alloc 错误?

java - 二维数组无法解析为变量

java - 字符串无法转换为int数组和ASCII

android - 在 Android 中使用自定义适配器和 SoftReference 时的性能建议

c - %i 或 %d 使用 printf() 在 C 中打印整数?

c - 如何释放c中双向链表程序的内存

c - 段错误(核心已转储)- C

c - 访问冲突写入位置插入数组

linux - 软虚拟内存限制 (ulimit -v)