将动态分配的2d字符数组传递给函数

时间:2016-10-19 16:36:32

标签: c++ c arrays

以下是数组的分配方式。

char** cArray =  malloc(10 * sizeof(char *)); 

int i;
for(i =0; i< 10; i++) { 
  cArray[i] = malloc(25 * sizeof(char));
}

如何使用此签名传递给函数:

sampleFunction(int max, char list[][max]){
  //Do something
};

尝试:

sampleFunction(25, cArray);

这给了我以下错误:

expected 'char (*)[(sizetype)(max)]' but argument is of type 'char **'

我也尝试过:

sampleFunction(int max, char* list[][max]){
  //Do something
};

sampleFunction(25, &cArray);

这给了我以下错误:

expected 'char * (*)[(sizetype)(max)]' but argument is of type 'char ***'

我也尝试过:

sampleFunction(int max, char* list[][max]){
  //Do something
};

sampleFunction(25, cArray);

这给了我以下错误:

expected 'char * (*)[(sizetype)(max)]' but argument is of type 'char **'

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

数组不是指针,指针不是数组。

第一个参数类型表示list是指向char数组的指针 cArray不是char*它是list的指针。

第二个说char*是指向cArray数组的指针,距离char**更远。

您需要传递正确的类型void sampleFunction(int max_rows, int max_columns, char** list){ for (int i = 0; i < max_rows; i++) for (int j = 0; j < max_columns; j++) list[i][j] = 0; } sampleFunction(10, 25, cArray); 和两个维度:

var returnItems=[];
                data.each(function() {
                    var rowIndex = $dataTable.fnGetPosition(this);
                    var selectedRow = $dataTable.fnGetData(rowIndex);
                    returnItems.push(
                        {
                            DeliveryAddress: selectedRow.DeliveryAddress,
                            Extension: selectedRow.Extension,
                            IsCourier: selectedRow.IsCourier,
                            Quantity: selectedRow.Quantity,
                            DeliveryAddressDetails: {
                                AddressDestinationDescription: selectedRow.DeliveryAddressDetails.AddressDestinationDescription,
                                AddressDestinationDetailId: selectedRow.DeliveryAddressDetails.AddressDestinationDetailId,
                                AddressDestinationName: selectedRow.DeliveryAddressDetails.AddressDestinationName,
                                AddressLine1: selectedRow.DeliveryAddressDetails.AddressLine1,
                                AddressLine2: selectedRow.DeliveryAddressDetails.AddressLine2,
                                AddressLine3: selectedRow.DeliveryAddressDetails.AddressLine3,
                                CityName: selectedRow.DeliveryAddressDetails.CityName,
                                PhoneNumber: selectedRow.DeliveryAddressDetails.PhoneNumber,
                                ZipCode: selectedRow.DeliveryAddressDetails.ZipCode
                            }
                        });
                });
        $("#myJson").val(JSON.stringify(returnItems));