type
Stack[T] = object
top: int
size: int
A: array[size, T]
This does not work as size is unknown at creation. How to create a ptr to array like in C?
Variable-length array is a new feature in C99, which is not used much and is not available in C++.
For variable size containers in C++ Vector data type is generally used, and in pure Nim we generally use seq data type. (For C interop you may consider UncheckedArray.)
This works but the array size is fixed. I want to specify the array size at object creation. Thanks for your help.
Variable-length array is a new feature in C99, which is not used much and is not available in C++.
Come again? This compiles and runs just fine in clang++. I mean, just fine for a C++ program.
// usage: <filename> <n> <el_1> <el_2> ... <el_n>
// example: ./a.out 5 8 4 3 1 6
// has output 8 4 3 1 6
#include <iostream>
int main(int argc, char * argv[]) {
int n = argv[1][0] - '0';
int a[n];
for (int i = 2; i < n + 2; ++i)
a[i - 2] = argv[i][0] - '0';
for (int i = 0; i < n; ++i)
std::cout << a[i] << ' ';
std::cout << std::endl;
}
You should use a seq. You would not need size as its part of seq as .len.
type
Stack[T] = object
top: int
A: seq[T]
If you NOT going interface with C there is no point in using C style arrays.
BUT if you want to emulate C ... some thing you should not need to do often if ever you can do it this way:
template `+`[T](p: ptr T, off: int): ptr T =
cast[ptr type(p[])](cast[ByteAddress](p) +% off * sizeof(p[]))
template `[]=`[T](p: ptr T, off: int, val: T) =
(p + off)[] = val
type
Stack[T] = object
top: int
size: int
A: ptr[T]
var stack = Stack[uint16]()
stack.top = 0
stack.size = 2
stack.A = cast[ptr uint16](alloc(sizeof(uint16) * stack.size))
stack.A[0] = uint16 12
stack.A[1] = uint16 12
* p = (int*) malloc (size * sizeof (int));
translated to nim:
p = cast[ptr cint](alloc(size * sizeof(cint)))