def make_alloc(loop_orders, dtype, sub, fortran='0'):
    """Generate C code to allocate outputs.

    Parameters
    ----------
    fortran : str
        A string included in the generated code. If it
        evaluate to non-zero, an ndarray in fortran order will be
        created, otherwise it will be c order.

    """
    type = dtype.upper()
    if type.startswith('THEANO_COMPLEX'):
        type = type.replace('THEANO_COMPLEX', 'NPY_COMPLEX')
    nd = len(loop_orders[0])
    init_dims = ''
    for i, candidates in enumerate(zip(*loop_orders)):
        for j, candidate in enumerate(candidates):
            if candidate != 'x':
                var = sub['lv%i' % j]
                init_dims += ('dims[%(i)s] = %(var)s_n%(candidate)s;\n' %
                    locals())
                break
        else:
            init_dims += 'dims[%(i)s] = 1;\n' % locals()
    return (
        """
    {
        npy_intp dims[%(nd)s];
        //npy_intp* dims = (npy_intp*)malloc(%(nd)s * sizeof(npy_intp));
        %(init_dims)s
        if (!%(olv)s) {
            %(olv)s = (PyArrayObject*)PyArray_EMPTY(%(nd)s, dims,
                                                    %(type)s,
                                                    %(fortran)s);
        }
        else {
            PyArray_Dims new_dims;
            new_dims.len = %(nd)s;
            new_dims.ptr = dims;
            PyObject* success = PyArray_Resize(%(olv)s, &new_dims, 0, NPY_CORDER);
            if (!success) {
                // If we can't resize the ndarray we have we can allocate a new one.
                PyErr_Clear();
                Py_XDECREF(%(olv)s);
                %(olv)s = (PyArrayObject*)PyArray_EMPTY(%(nd)s, dims, %(type)s, 0);
            } else {
                Py_DECREF(success);
            }
        }
        if (!%(olv)s) {
            %(fail)s
        }
    }
    """
         % dict(locals(), **sub))
