Hello
I have tried it :
a = "abc"
p: ptr string
echo(repr(a))
echo(repr(addr(a)))
p = addr(a) #The question : why not p = a ?
echo(repr(p))
echo(repr(addr(p)))
echo(a[0])
echo(p[0])
why not p = a ?
Because Nim is statically typed. In your example a is a Nim string, and p a pointer to a Nim string. So data types are different. When you apply addr() to a string, you get a pointer to it. That is similar as it is in C++, where you have C++ strings and can have pointers or references to that string.
For current Nim you have to take into account that Nim strings are garbage collected, so their memory may be freed automatically. Personally I would avoid using low level operations like addr() for garbage collected Nim objects whenever possible. For example, it may be OK to pass the addr() of the first element in a seq or string to a C library function, when that function copy that data. But problems may occur, when that function uses that data while GC thinks that memory chunk is unused and frees it.
Thank you
and i accept the second part of your answer, BUT the pointer isn't clear yet
if you try the given example you see :
a[0] ---> 'a'
p[0] ---> 'a' too. <-- why not similar thing like ('*'p)[0] because p and a are different things
in GOLANG :
var s string = "alma"
p:=&s
// fmt.Println(&s)
// fmt.Println(p)
// fmt.Println(&p)
fmt.Println(('*'p)[0]) -- this work, because this is logical
but p[0] -doesn't work , because p is the address of s, not s
Sorry for '*', but the editor give me when is try to submit , this : "Error: input(17, 18) Error: '*' expected"
OK, I think I see your problem.
In Nim an empty subscript [] notation can be used to derefer a reference or ptr. So if p is a pointer to string, in C++ you would write '*'p to dereference it, but in Nim you write p[]. And in Nim you can write p[n] to access the n'th character in that string. I would guess that p[][n] == p[n] but I have never tried if that compiles. In C++ we could write ('*'p)[0] to access the first character, in Nim that is p[0]. That is easier to write, and I think that implies no restrictions, as we do no pointer arithmetic in Nim like p++ in C.
Note: I put wrong '' around the star to make forum work...