2012-01-29 42 views
2

我有一个指向指针的指针,因为我无法将动态数组传递给函数。但是,如果我想用预制数据初始化该指针指针,我该如何设置它,因为数组的{a,b,c}表示法不适用于指针?如何使用预制数据初始化指针指针?

+1

为什么你不能将动态数组传递给函数?什么是函数签名?你对动态数组有什么了解?发布相关代码,例如要使用的函数,要传递的数据,然后说明问题! – Nawaz 2012-01-29 04:16:16

+0

我不想被传递给函数时定义数组的大小所限制。我想有n个数组和x个y数组。 – BLaZuRE 2012-01-29 04:53:15

+0

这意味着,你不知道什么* dynamic *数组,是吗? – Nawaz 2012-01-29 05:07:31

回答

1

你可以这样做:

static int row1[] = {1, 2, 3}; 
static int row2[] = {4, 5, 6, 7}; 
static int row3[] = {8, 9, 10, 11, 12, 13}; 
static int *pptr[] = {row1, row2, row3}; 

在这一点上,pptr可以分配到一个int**

int **p = pptr; 
+0

谢谢,这个解决方案有效。我不喜欢它,因为在我的脑海中,我认为有一个更优雅的解决方案,或者我做错了矩阵。它的工作原理虽然很直观。 – BLaZuRE 2012-01-29 04:50:11

+1

@BLaZuRE鉴于您可以使用C++库的强大功能,所以选择执行矩阵的双指针确实看起来并不理想。一个更好的选择是矢量矢量,因为内存将自动为您管理。 – dasblinkenlight 2012-01-29 13:59:53

0

[如果你需要一个双*这答案只有相关。你的问题是编辑说指针的指针 - 如果这是你需要什么,这个答案是不相关]

你可以这样做,而不是:

double fValues[3] = { 1, 2, 3 };

变量fValues已经是一个指针 - 。没有[]的数组变量是指向数组的第一个元素的指针。这不是一个动态数组,所以你不需要分配/释放它的内存。

假设你的函数,需要一个双指针看起来是这样的:

void Func(double* pDbl) {...}

你这样称呼它:

Func(fValues);

0

可以递归创建小的动态数组像这样:

#include <stddef.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdio.h> 

typedef struct 
{ 
    int* pValues; 
    size_t Count; 
} List; 

const List ListEnd = { NULL, 0 }; 

List NewList(int Value, List SubList) 
{ 
    List l; 

    l.Count = SubList.Count + 1; 

    if (SubList.Count == 0) 
    { 
    l.pValues = malloc(sizeof(int)); 
    } 
    else 
    { 
    l.pValues = realloc(SubList.pValues, l.Count * sizeof(int)); 
    } 

    if (l.pValues == NULL) 
    { 
    // do proper error handling here 
    abort(); 
    } 

    // moving data isn't necessary if the list elements are 
    // in the reverse order 
    memmove(&l.pValues[1], &l.pValues[0], SubList.Count * sizeof(int)); 

    l.pValues[0] = Value; 

    return l; 
} 

void PrintDynArr(int* pValues, size_t Count) 
{ 
    while (Count--) 
    { 
    printf("%d\n", *pValues++); 
    } 
} 

int main(void) 
{ 
    int* p; 

    PrintDynArr(p = NewList(1, 
        NewList(2, 
        NewList(3, 
        NewList(4, ListEnd)))).pValues, 
       4); 

    free(p); 

    return 0; 
} 

输出:

1 
2 
3 
4 
+0

你为什么要这样做,而不是仅仅使用'std :: vector'? – 2012-01-29 18:02:55