Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to find the size of integer without using sizeof function. I wrote something like this but it doesn't work properly. It outputs 1. Please correct me. Here is my code.

int intSize() {
 int intArray[10];
 int *intPtr1;
 int *intPtr2;
 intPtr1 = intArray;
 intPtr2 = intPtr1 + 1;
 return intPtr2-intPtr1;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

Cast the pointer to char* before using pointer arithmetic.

int intSize() {
  int intArray[10];
  char* ptr1 = reinterpret_cast<char*>(intArray);
  char* ptr2 = reinterpret_cast<char*>(intArray+1);
  return ptr2-ptr1;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...