无法找到C中的数组的长度? [英] Having trouble finding the length of an array in C?

查看:176
本文介绍了无法找到C中的数组的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  ç动态内存分配和sizeof()

我试图找到保持16 MIB一块巨大的缓存块,并试图通过每次抽出时间访问不同的元素。我只是不能写数组的长度。
我如何写一个for循环遍历数组。我需要阵列的长度;我怎么能找到呢?我曾尝试的sizeof(A)/ sizeof的(A [0])但是,这并不工作或我做错了什么,因为我的任务表告诉我,它可以容纳4万元的..

I am trying to find the cache block by keeping a huge block of 16 MiB and by trying to access different elements each time to find the time. I just can't write the length of the array. How can I write a for loop to iterate over the array. I need the length of the array; how can I find that? I have tried sizeof(a)/sizeof(a[0]) but this doesn't work or I am doing something wrong because my assignment sheet tells me it can hold 4 million int's..

register *a;
a = malloc(16777216);
int i;
for (i = 0; i < sizeof(a)/sizeof(a[0]); i = i + 1) {

    printf("\ni = %d", i);
}

这仅打印照片i = 0 I = 1。

This only prints i = 0 i = 1.

推荐答案

在code 的sizeof(A)只是返回指针的大小注册* A ,并且是完全无关的数组的大小 A 点。

The code sizeof(a) simply returns the size of the pointer register *a, and is completely unrelated to the size of the array that a points to.

C数组不跟踪他们多少项目包含的内容。您可以使用此语法仅当数组的大小是在编译时已知。但你不能与分配这样一个数组做到这一点。

C arrays do not track how many items they contain. You can use this syntax only if the size of the array is known at compile time. But you can't do it with an array allocated this way.

有关这个任务,你需要自己跟踪此信息。您可以在值存储在一个变量,或者你可以用一个特殊的值,表示它的阵列(就像我们做C字符串)。

For this task, you'll need to track this information yourself. You can store that value in a variable, or you could append an array element with a special value that indicates it's the end of the array (much like we do with C strings).

这篇关于无法找到C中的数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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