如何检查指针是否指向数组或单个int或char [英] How to check if a pointer points to an array or single int or char

查看:62
本文介绍了如何检查指针是否指向数组或单个int或char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道指针是指向数组还是单个整数.我有一个函数,需要两个指针( int char )作为输入,并判断一个指针是指向数组还是指向单个整数.

I want to know whether a pointer is pointing to an array or single integer. I have a function which takes two pointer (int and char) as input and tell whether a pointer is pointing to an array or single integer.

pointer=pointer+4;
pointer1=pointer1+4;

这是个好主意吗?

推荐答案

就像其他人在这里说的那样,C不知道指针指向的是什么.但是,如果您选择沿着这条路径走,则可以将前哨值放在数组的整数或第一位置,以表明它是什么.

Like others have said here, C doesn't know what a pointer is pointing to. However if you should choose to go down this path, you could put a sentinel value in the integer or first position in the array to indicate what it is...

#define ARRAY_SENTINEL -1

int x = 0;
int x_array[3] = {ARRAY_SENTINEL, 7, 11};

pointer = &x_array[0];

if (*pointer == ARRAY_SENTINEL)
{
   // do some crazy stuff
}

pointer = &x;

if (*pointer != ARRAY_SENTINEL)
{
   // do some more crazy stuff
}

这篇关于如何检查指针是否指向数组或单个int或char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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