LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-21-2013, 09:41 PM   #1
atlantis43
Member
 
Registered: Feb 2013
Posts: 289

Rep: Reputation: Disabled
use of unsigned cast with array pointers


Hoping that someone can explain why (unsigned) cast is needed in the following code which gives result of 4,while leaving out cast yields result 1:
Code:
#include <stdio.h>

int main(void){

int array2[2];
int *ptr3;

ptr3 = array2;
printf("%d\n", (unsigned)(ptr3+1)-(unsigned)ptr3);
printf("%d\n", (ptr3+1)-ptr3);

return 0;
}
 
Old 09-21-2013, 10:11 PM   #2
rknichols
Senior Member
 
Registered: Aug 2009
Distribution: Rocky Linux
Posts: 4,784

Rep: Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214Reputation: 2214
Sure. By definition, the expression "(ptr3+1)-ptr3" yields a value which when added to ptr3 yields ptr3+1, and that value is simply 1 since the scaling by sizeof(*ptr3) is implied in the addition.

When you do the (unsigned) typecast, the pointer type is lost, so the result is a number which when added to an integer containing the bit pattern of ptr3 will yield an integer containing the bit pattern of (ptr3+1). The addition is done on the pointer type, and gets the implied scaling, but the subtraction is simply the difference between two integers.
 
1 members found this post helpful.
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] unsigned integer array syntax error in eclipse CDT Zoophobus Programming 7 12-15-2011 09:36 AM
Array of pointers to structs grob115 Programming 7 11-20-2011 10:49 AM
How to cast a char ptr to an array (to prevent warning, it does work) Owen_Townsend Linux - General 1 09-03-2008 09:14 PM
array of pointers to struct in c : how? moob8 Programming 6 11-21-2006 11:13 AM
c array of pointers greg108 Programming 10 08-17-2005 10:25 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 12:37 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration