S
Spiro Trikaliotis
Hello,
I have a question regarding subtracting a pointer from another one.
Assume I have two pointers p1 and p2, which both point to a memory area
obtained with malloc(). Assume p1 = p2 + some value c.
Now, I want to obtain the difference between the two, that is, the value
c. Which type must I use for c?
I searched around and did not find a definitive answer (not even in the
FAQ). Anyway, http://c-faq.com/malloc/realloc.html has a code sample
which uses:
int tmpoffset;
p = malloc(10);
strcpy(p, "Hello,");/* p is a string */
p2 = strchr(p, ',');/* p2 points into that string */
tmpoffset = p2 - p;
Thus, this examples assumes that an int should be sufficient (or that
example is broken).
Unfortunately, my compiler complains on the "tmpoffset = p2 -p;" line:
file.c(745): error C4242: '=' : conversion from '__int64' to 'int', possible loss of data
(Yes, this is a 64 bit MS compiler, but that should not matter.)
Of course, I could just use __int64 type, but this does not seem the
best portable way for me. I could cast p2-p, as I know the difference
can't be that big not to fit into an int, but this is no good solution
either. Additionally, I doubt size_t to be a good candidate here,
either.
So, my question is: Thinking of portability, which type should I use
here? Or is the MS compiler wrong?
Thanks,
Spiro.
I have a question regarding subtracting a pointer from another one.
Assume I have two pointers p1 and p2, which both point to a memory area
obtained with malloc(). Assume p1 = p2 + some value c.
Now, I want to obtain the difference between the two, that is, the value
c. Which type must I use for c?
I searched around and did not find a definitive answer (not even in the
FAQ). Anyway, http://c-faq.com/malloc/realloc.html has a code sample
which uses:
int tmpoffset;
p = malloc(10);
strcpy(p, "Hello,");/* p is a string */
p2 = strchr(p, ',');/* p2 points into that string */
tmpoffset = p2 - p;
Thus, this examples assumes that an int should be sufficient (or that
example is broken).
Unfortunately, my compiler complains on the "tmpoffset = p2 -p;" line:
file.c(745): error C4242: '=' : conversion from '__int64' to 'int', possible loss of data
(Yes, this is a 64 bit MS compiler, but that should not matter.)
Of course, I could just use __int64 type, but this does not seem the
best portable way for me. I could cast p2-p, as I know the difference
can't be that big not to fit into an int, but this is no good solution
either. Additionally, I doubt size_t to be a good candidate here,
either.
So, my question is: Thinking of portability, which type should I use
here? Or is the MS compiler wrong?
Thanks,
Spiro.