指针算术 [英] pointer arithmatic

查看:58
本文介绍了指针算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以减去指向由malloc分配的两个不同位置内存的两个相同类型的指针。


例如。

#include< stdlib.h>

int main(无效)

{


unsigned char * c_ptr;

unsigned char * c_ptr1;

unsigned char * c_ptr2;

int diff;


c_ptr = malloc(100 * sizeof(char));

c_ptr1 = c_ptr + 5;

c_ptr2 = c_ptr + 10;

diff = c_ptr2 - c_ptr1; / *有效吗? * /

}

减法(c_ptr2 - c_ptr1)是否有效?

是否保证差异?将永远是5?

Can I subtract two pointers of same type that are pointing to the two
different location of memory allocated by malloc.

eg.
#include <stdlib.h>
int main(void)
{

unsigned char *c_ptr;
unsigned char *c_ptr1;
unsigned char *c_ptr2;
int diff;

c_ptr = malloc(100 * sizeof(char));
c_ptr1 = c_ptr + 5;
c_ptr2 = c_ptr + 10;
diff = c_ptr2 - c_ptr1; /* Is it valid ? */
}
Is the subtraction ( c_ptr2 - c_ptr1 ) valid ?
Is it guaranteed that "diff" will always be 5 ?

推荐答案



ju ********** @ yahoo.co.in 写道:
我能否减去两个指针相同类型的,指向malloc分配的两个不同位置的内存。


是的,只要它们都指向同一个对象中的某个地方

由malloc分配。

例如。
#include< stdlib.h>
int main(void)

unsigned char * c_ptr;
unsigned char * c_ptr1;
unsigned char * c_ptr2;
int diff;

c_ptr = malloc(100 * sizeof(char));
c_ptr1 = c_ptr + 5;
c_ptr2 = c_ptr + 10;
diff = c_ptr2 - c_ptr1; / *有效吗? * /


这里缺少退货声明。

}
减法(c_ptr2 - c_ptr1)有效吗?


是。

是否保证差异将永远是5?
Can I subtract two pointers of same type that are pointing to the two
different location of memory allocated by malloc.
Yes, as long as they both point to some place in the same object
allocated by malloc.
eg.
#include <stdlib.h>
int main(void)
{

unsigned char *c_ptr;
unsigned char *c_ptr1;
unsigned char *c_ptr2;
int diff;

c_ptr = malloc(100 * sizeof(char));
c_ptr1 = c_ptr + 5;
c_ptr2 = c_ptr + 10;
diff = c_ptr2 - c_ptr1; /* Is it valid ? */
Missing return statement here.
}
Is the subtraction ( c_ptr2 - c_ptr1 ) valid ?
Yes.
Is it guaranteed that "diff" will always be 5 ?




是的。


Robert Gamble



Yes.

Robert Gamble

< br>

ju ********** @ yahoo.co.in 写道:

我可以减去指向由malloc分配的两个不同内存位置的两个相同类型的指针。

Can I subtract two pointers of same type that are pointing to the
two different location of memory allocated by malloc.




No.


-

我的结论是有两种构建软件的方法

设计:一种方法是让它变得如此简单,以至于明显没有缺点,另一种方法就是让它变得如此复杂

没有显而易见的缺陷。 - C. A. R. Hoare



No.

--
"I conclude that there are two ways of constructing a software
design: One way is to make it so simple that there are obviously
no deficiencies and the other way is to make it so complicated
that there are no obvious deficiencies." -- C. A. R. Hoare


嗯,至少你的答案是简洁的。是的但也是正确的。两个指针之间的
整数差异可能毫无意义,但指针

减法总是有效的。

Well, at least your answer is concise. Were it but also correct. The
integer difference between two pointers may be meaningless, but pointer
subtraction is always valid.


这篇关于指针算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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