C:确保你从一个数组返回元素是正确的 [英] C : Making sure the element you return from an array is correct

查看:79
本文介绍了C:确保你从一个数组返回元素是正确的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这一块 C code的:

Say we have this piece of C code:

int x[] = {1, 2, 3, 4, 5};

printf("%d", *(x + 1)); //prints 2
printf("%d", *(x + 500)); //prints 7209065 (...?)

你可以从第二个电话看,还是返回的东西...但它的垃圾。

As you can see from the second call, it still returns something...but it's garbage.

那么请问,你如何处理用C这样的情况?也就是说,你怎么知道,如果返回的元素是真正存在于数组或只是垃圾的因素呢?

So I ask, how do you handle such a case in C? ie, how do you know if the returned element is really an element that exists in the array or just garbage ?

推荐答案

添加持有数组的长度,只要你想访问数组确保您的数组的边界内的另一个变量。

Add another variable that holds the length of the array, and whenever you want to access the array make sure you are within the bounds of the array.

这篇关于C:确保你从一个数组返回元素是正确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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