1

for example, i want to write a function with this signature: int foo(char[]) and to call it using char[5] x; foo(x).

At the moment i get a compile error stating that char[] isn't the same as char[5].

I thought of writing: int foo(uint SIZE)(char[SIZE]) but then I have to explicitly set the length when calling foo: foo!5(x) for the example before.

EDIT: you guys are correct, my function actually looks like foo(ref char[]) and I have declared it @nogc. What I want to do is to fill a given static array with data. In a broader sense, I'm trying to implement a degenerate format function because the standard library one is definitely using the GC and I can't call it from my other non GC code. Any ideas about that as well?

ordahan
  • 187
  • 9
  • 2
    static array should be implicitly convertible to dynamic arrays, also the compiler can infer the SIZE argument – ratchet freak Sep 24 '14 at 09:27
  • 1
    see the bottom of [Arrays](http://dlang.org/arrays.html#conversions). As @ratchetfreak said, `T[dim]` converts implicitly to `T[]`. Can you post an example that produces this error? – rcorre Sep 24 '14 at 12:37
  • 2
    that implicit conversion really *shouldn't* be allowed (unless scope escape analysis was present, but it isn't) - it easily leads to crashes in a number of situations and plays a role in breaking the immutability guarantee! That's a gaping hole in memory safety in the spec and ought to be fixed - don't depend on it. Instead, when you know it is safe (such as passing the array to a function where it won't be stored), explicitly slice it with the slice operator: `foo(x[])` – Adam D. Ruppe Sep 24 '14 at 13:48
  • @ratchetfreak - how does that happen? Should I just omit the size? – ordahan Sep 27 '14 at 14:10

1 Answers1

2

char[] is indeed not the same as char[5], but nothing prevents you from passing static array as an argument to a function which has char[] parameter because of the implicit conversion.

Example:

module so.d26013262;

import std.stdio;

int getSize(int[] arr) {
    return arr.length;
}

void main(string[] args) {
    int[5] starr;
    int[] dyarr = [1, 3, 2];

    writeln(getSize(starr));
    writeln(getSize(dyarr));
}

Output:

5
3

My guess is that you are getting error somewhere else...

DejanLekic
  • 18,787
  • 4
  • 46
  • 77