Ç - 动态数组 [英] C - dynamic arrays

查看:132
本文介绍了Ç - 动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白指针如何使用C数组。下面是一些code我:

I don't quite understand how pointers work with C arrays. Here's some code I got:

int arrayOne[] = {1, 2, 3};
int arrayTwo[] = {4, 5, 6, 7};

int **arrayThree = (int **)malloc(2 * sizeof(int));
arrayThree[0] = arrayOne;
arrayThree[1] = arrayTwo;

for (int i = 0; i < 2; i++) {
    int *array = arrayThree[i];
    int length = sizeof(array) / sizeof(int);
    for (int j = 0; j < length; j++)
        printf("arrayThree[%d][%d] = %d\n", i, j, array[j]);
}

我本来期望这输出以下内容:

I would have expected this to output the following:

arrayThree[0][0] = 1
arrayThree[0][1] = 2
arrayThree[0][2] = 3
arrayThree[1][0] = 4
arrayThree[1][1] = 5
arrayThree[1][2] = 6
arrayThree[1][3] = 7

这实际打印出来的是:

What it actually prints out is:

arrayThree[0][0] = 1
arrayThree[0][1] = 2
arrayThree[1][0] = 4
arrayThree[1][1] = 5

为什么?!

推荐答案

的sizeof(阵列)是一个指针,这恰好是两倍的大小的 INT 您的平台。

sizeof(array) is the size of a pointer, which just happens to be the twice the size of an int on your platform.

有没有办法得到C.你一个数组的长度只需要自己记住它。

There's no way to get the length of an array in C. You just have to remember it yourself.

这篇关于Ç - 动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆