473,883 Members | 1,841 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why multiplication not allowed?

Hi,

Why multiplication of pointers is not allowed?
Till now I only know this, but not the reason why!

PS: As a rule, I searched the FAQ, but could not
find an answer.

--
Vijay Kumar R Zanvar
My Home Page - http://www.geocities.com/vijoeyz/
Nov 14 '05
87 11270
Kevin Goodsell <us************ *********@never box.com> wrote in message news:<gw******* ***********@new sread1.news.pas .earthlink.net> ...
Flash Gordon wrote:

It's not holding your hand, it's just not providing something that makes
no sense. You can always side-step the limitation by casting the
pointers to long long and multiplying them, although there is no
guarantee that they will actually fit in to a long long.


FYI, there is a guarantee in C99 that an object pointer will fit in a
intptr_t, if that type is provided.


More specifically, as an aside, the conversion back to an equivalent
void * is guaranteed, something which isn't the case for other integer
types, not even intmax_t.

--
Peter
Nov 14 '05 #41
Peter Nilsson wrote:
Kevin Goodsell <us************ *********@never box.com> wrote in message news:<gw******* ***********@new sread1.news.pas .earthlink.net> ...
Flash Gordon wrote:
It's not holding your hand, it's just not providing something that makes
no sense. You can always side-step the limitation by casting the
pointers to long long and multiplying them, although there is no
guarantee that they will actually fit in to a long long.


FYI, there is a guarantee in C99 that an object pointer will fit in a
intptr_t, if that type is provided.

More specifically, as an aside, the conversion back to an equivalent
void * is guaranteed, something which isn't the case for other integer
types, not even intmax_t.


Yes, the standard only explicitly says you can convert from void* to
intptr_t, then back to void* and the result will compare equal to the
original void*. Other pointer types *should* also work (by which I mean
that it would make sense, and people probably expect them to work), but
I don't know if or where in the standard this is guaranteed.

As for intmax_t, I would expect that it could be used in place of
intptr_t as long as intptr_t exists - my reasoning being that the only
thing which would prevent an integer type from holding a pointer value
without loss is if the integer type is not wide enough, and intmax_t
must be at least as wide as intptr_t. I don't know if that is correct,
though.

I should take a good look at the section of the standard dealing with
conversion between integers and pointers, I guess.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #42
On Wed, 7 Jan 2004, Christopher Benson-Manica wrote:
If p is a pointer pointing to a memory region of sufficient size,

(p+5)==(p+5*siz eof(*p))
Mixing C and asm sides of brain?-)

right? Likewise for p-5. Then (I suggest),

(p*5)==(5*sizeo f(*p))

would be sensible. Not needed, but meaningful, yes?


Not really, but I'd imagine that sizeof(*(p*5)) == 5*sizeof(*p) would
have some odd symmetry, if that's what you're after.. as in:

pointers -> points (index, size)
scalars -> vectors (index, 0)

Nov 14 '05 #43
Alan Balmer wrote:
You didn't answer the question. What meaning would you ascribe to the
result of the operation?


If you'd read on, you'd have seen that I really wouldn't have. Any more
than I would have been able to ascribe meaning to the result of adding a
random integral value to an arbitrary pointer. My whole point is that in
some languages (not C, but C's immediate ancestors and some languages
not connected with C at all), you can treat a pointer as you would any
other integral type of that width. Which includes doing absolutely
nonsensical things to it.

Obviously, I'm in a minority here. I didn't expect it to be otherwise,
given the bizarreness of the whole notion of multiplication being
applied to pointers.
Nov 14 '05 #44
Kevin Goodsell wrote:
August Derleth wrote:
Kevin Goodsell wrote:

The question Ben is asking is, what would you propose pointer
multiplication do? How would you define the operation? I can't think
of any way in which multiplying a pointer by any other value would be
useful or even meaningful.
The way I reason is like this: If I take i and assign an address to it
(that is, I make it a pointer), i is the name of a block of memory
that holds a certain string of bits or trits or decimal digits that
compose that address. At this layer of abstraction, it's no different
from an int or a float. Since I can multiply two ints and stand a good
chance at getting a meaningful result, why not two pointers? Or an int
and a pointer?

Because the result is *not* meaningful for pointers.


I'm not saying it would be. I'm just saying that some languages allow
it, and that I'm surprised that C isn't one of them.

Your question is somewhat like asking "why can't I assign to a
function?" or "why can't I take the square root of a struct?" There's
just no logical reason why you *should* be able to.
My response to this is that the compiler shouldn't hold my hand that
much. As Kernighan said, "If you want PL/I, you know where to get it."
In Forth, for example, a pointer is simply a bunch of bits on the
stack, and you can do unto a pointer the same as you can do unto an
int or anything else. The only extra feature is that, if you
dereference it, you stand a good chance of getting something meaningful.

I suppose if I want Forth, I know where to find it.


All I can say to this is that I'm glad you didn't design C.


Me, too. I probably would have designed a language too tied to the PDP's
instruction set and not easily portable to anything else.

You might also be interested in BCPL. I know almost nothing about it,
but I believe I read that it only had 1 type: the machine word. I
imagine this would give you the kind of complete freedom from
hand-holding that you seem to want. (It's also possible that the
language I'm thinking of is B, not BCPL.)


I'm aware of that, and that's partially what I was thinking of. In B and
BCPL, a rather Forth-like notion of `Trust the programmer' pervades the
concept of types. (Or maybe `In Forth, a BCPL-like notion ... ' ;))

C's notion of types is strict enough to be helpful and loose enough to
not be obnoxious, IMHO, even though it occasionally leads to threads
like these.
Nov 14 '05 #45
Keith Thompson wrote:
August Derleth <em***@for.addr ess> writes:
Kevin Goodsell wrote:
[...]
The question Ben is asking is, what would you propose pointer
multiplicati on do? How would you define the operation? I can't think
of any way in which multiplying a pointer by any other value would
be useful or even meaningful.


The way I reason is like this: If I take i and assign an address to it
(that is, I make it a pointer), i is the name of a block of memory
that holds a certain string of bits or trits or decimal digits that
compose that address. At this layer of abstraction, it's no different
from an int or a float. Since I can multiply two ints and stand a good
chance at getting a meaningful result, why not two pointers? Or an int
and a pointer?

Because you *can't* multiply two pointers, or an int and a pointer,
and stand a chance at getting a meaningful result.


Which doesn't stop BCPL, for instance. :)

Pointers are not integers. Pointer arithmetic in C is not defined in
terms of treating the bit patterns composing the pointer values as
integers and performing integer arithmetic on them; it's defined in
terms of what object the resulting pointer value points to.
I know that. I am satisfied with the existing pointer arithmetic,
acutally, even though I posited my remarks from the perspective of
changing it.

For example, if p is a pointer, the machine-level operations that are
performed to evaluate the expression (p + 4) depend on the type of p.
If p is a char*, (p + 4) points to a location 4 bytes "after" the
location pointed to by p; if p is an int*, (p + 4) points
4*sizeof(int) bytes "after" the location pointed to by p. If p is a
void*, the expression (p + 4) is illegal (though some compilers may
support it as a language extension (unwisely, IMHO)).
This is where my ideas about multiplication fall down in one respect:
Addition (by positive and negative numbers) is scaled, but there's no
meaningful way to scale multiplication. Or division, for that matter.
And how would you scale the square root?

We could invent ways, surely, but it's hardly worth it.

(If you want to know, I was imagining pointers as being treated like
integers in my imaginary C-like language.)

Another example: On Cray vector machines, a machine address points to
a 64-bit word. The C compiler implements 8-bit chars (CHAR_BIT == 8)
by "cheating" a little. (I put the word "cheating" in quotation marks
because what the C compiler does is perfectly legitimate; it just
doesn't map directly to the underlying hardware.) A char* is
implemented as a word address with a byte offset kludged into the
high-order 3 bits. (I actually don't know how much hardware support
there is for this format.) Multiplying two such pointers makes as
much sense as taking the square root of a struct.
This is fascinating. Which compiler do you use? Does gcc support the
Cray vector machines?

It's fascinating, and it makes my ideas sound rather foolish. You could
multiply two such pointers, but the machine-level semantics would always
be in doubt and the result would be universally meaningless.

If, for some reason, you want to treat the contents of two pointers as
if they were integers, multiply them, and store the resuting integer
bit pattern into a pointer, you can do so. I don't think a cast from
a pointer to an integer of the appropriate size, or vice versa, is
guaranteed to just copy the bits, but it probably does so on most or
all implementations . If you're concerned about that, you can use
memcpy(), which is guaranteed to copy the bits. Using explicit
conversions, you can multiply two pointers (treating the pointers' bit
patterns as integers and treating the resulting integer bit pattern as
a pointer) as easily as you can take the square root of a struct
(treating the struct's bit pattern as a double). The compiler won't
hold your hand while you do this, but it won't stop you. Of course,
you'll invoke undefined behavior, and I can't think of any possible
use for the result.


All of that is fair enough, and it's all I can reasonably expect. After
all, the compiler won't hold my hand, will it? :) memcpy() seems like a
somewhat sideways means of achieving this, but its semantics are
obvious. Whereas the semantics of multiplying two pointers would not be.
Nov 14 '05 #46
Barry Schwarz wrote:

(snip)
Why multiplication of pointers is not allowed?
Till now I only know this, but not the reason why!

(snip)
Adding an int to a pointer results in pointing to something a
specified distance further to the "right" in memory. Subtracting an int from a pointer results in pointing to something a
specified distance further to the "left" in memory. Subtracting one pointer from another results in how far apart the two
memory locations are.


An expression could be properly absolute or relocatable, even if it
contained multiplication of pointers. The number of uses are small
enough that I am not surprised it isn't allowed. How about:

char *s,*t;
s=2*t-s;
s=3*t-2*s;

(I know some assemblers that allow relocation factors
of -1, 0, 1, or 2.)

-- glen

Nov 14 '05 #47
Christopher Benson-Manica <at***@nospam.c yberspace.org> scribbled the following:
Keith Thompson <ks***@mib.or g> spoke thus:
Because you *can't* multiply two pointers, or an int and a pointer,
and stand a chance at getting a meaningful result.
True enough. But let me suggest something, assuming I don't make a
mistake in my reasoning before doing so. If p is a pointer pointing to a memory region of sufficient size, (p+5)==(p+5*siz eof(*p))


You mean
(p+5)==((char *)p+5*sizeof(*p )),
natch.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"My absolute aspect is probably..."
- Mato Valtonen
Nov 14 '05 #48
James Dow Allen wrote:
While I've never felt an urge to multiply pointers, there
is a situation where adding them is quite legitimate:
char *rcopy, *q, *r;
. . .
strcpy(rcopy, r);
q = index(r, '*');
. . .
/* Now point to the '*' in the copy */
foobar(rcopy + q - r);
My first C program using index, after using a similar function
in other languages, did something like i=index(r,"*")-r;

It made the NULL test more complicated, though.
(Please don't write in to tell me I forgot to allocate space for rcopy, etc.
This is just a minimal illustration of the point.) Although the intermediate expression (rcopy + q) has the illegal form
of (ptr + ptr) the net expression is OK.
Well, for (char*), ok.
I was disappointed when gcc rejected my construction like this, depending
on how I parenthesized it. It seems like it shouldn't be hard to support.


Things get more interesting with pointers to larger types.

int *b,*c;
char *a;

a=a+b-c;

Remember that pointer addition is done in units of the type
pointed to. Pointer-pointer is done so that the result is
in such units.

In this case, the result would be different.

Also, consider that the int pointers could (illegally) point
to non-aligned addresses.

-- glen

Nov 14 '05 #49
Joona I Palaste wrote:

(snip)
Yes, this is an obsolete feature of C. =+ and =- originally meant the
same as += and -=. Whoever designed them that way must have been
drinking something really strong. AFAIK they were dropped when ISO
standardised C.
That the interviewer still clung to the obsolete meanings of those
operators makes me feel that he wasn't the proper person to interview
you about C.

I have used compilers that allowed them for compatibility. I still
always put a space between = and -, like i= -1; to be sure.

(I think the compiler gave a warning, though.)

-- glen

Nov 14 '05 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2296
by: Soeren Sonnenburg | last post by:
Hi all, Just having started with python, I feel that simple array operations '*' and '+' don't do multiplication/addition but instead extend/join an array: a= >>> b= >>> a+b
9
8007
by: Ralf Hildebrandt | last post by:
Hi all! First of all: I am a C-newbie. I have noticed a "strange" behavior with the standart integer multiplication. The code is: void main(void)
11
4887
by: mjdeesh_hi | last post by:
How can we perfom multiplication programatically without using + or * operator. Can any one help out in this one. Jagadeesh.
11
5245
by: Skybuck Flying | last post by:
Hello, type Tbig = array of byte; vAddTable : array of array of byte; // = value // = transport/carry vMulTable : array of array of byte;
1
9181
by: Sozos | last post by:
Hi guys. I have a problem with writing the base case for the following matrix multiplication function I have implemented. Please help. #define index(i,j,power) (((i)<<(power))+(j)) void recMultiply(int i, int j, float a, int k, int l, float b, int x, int y, float c, int s); int i, j, k, s, matrixsize, blocksize, jj, kk, power, bsize; float sum, maxr, total=0.0, startmult, finishmult, multtime; float* A = NULL; float* B = NULL;
0
11153
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10757
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10420
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7975
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7134
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5804
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6002
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3239
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.