Question about Pointer Arithmetic

16 views
Skip to first unread message

Matthew Maycock

unread,
Oct 28, 2019, 3:39:56 AM10/28/19
to pure-lang
Hello!

I just did a mac ports install of Pure (the entire category) and have been playing around with it today. I am trying to do pointer arithmetic to add a NUL after doing an fread to a buffer, but am running into some issues:

> using pointers;
> c = malloc 123;
> (c+1) - c;
-1048415L

and if I try it again I get something different:

> using pointers;
> c = malloc 123;
> (c+1) - c;
79681L

and so on. Any clue what's going on here? I'm on OSX 10.14.6 and the banner says Pure 0.68 (x86_64-apple-darwin18.2.0).


Regards!

~Matthew Maycock

Albert Graef

unread,
Oct 28, 2019, 4:23:57 AM10/28/19
to pure...@googlegroups.com
Hi Matthew,

welcome to the list!

On Mon, Oct 28, 2019 at 8:39 AM Matthew Maycock <umma...@gmail.com> wrote:

> using pointers;
> c = malloc 123;
> (c+1) - c;
-1048415L

and if I try it again I get something different:

That's because you've defined c as a function, not as a variable. In Pure, a function will be evaluated each time you call it, even if it has no parameters. Try evaluating just `c` by itself and you'll see what I mean.

To create a global variable which stores the value returned by malloc, use this instead:

let c = malloc 123;

Or, if you only need this value temporarily inside another function, you'd use a local variable definition (`when` clause) like this:

foo n = do_something_with_c_here when c = malloc n end;

HTH,
Albert

--
Dr. Albert Gr"af
Computer Music Research Group, JGU Mainz, Germany
Email: agg...@gmail.com, web: https://agraef.github.io/
Reply all
Reply to author
Forward
0 new messages