2012-04-17 73 views
0

我有指針的二維數組(字符串)開始C:實施rownames的功能

char *result[7000][14]; 

我想寫返回第一個字符串中的每個「行」的功能。

這裏是我的嘗試:

char *getRownames (int a, int b, char *matrix[a][b]) 
{ 
    char *rownames[a]; 
    for(int i=0;i<a;i++){ 
     rownames[i] = malloc(strlen(matrix[i][0])+1); 
     strcpy(rownames[i],matrix[i][0]); 
    } 

    return *rownames; 
} 

然後

char *names = getRownames(7000, 14, result); 

我得到,說衝突的類型getRowNames錯誤。仍然習慣於C並且不得不分配我自己的記憶。

+0

rownames是一個指針指針,所以char ** names = getRownames(7000,14,result);可能工作 – Chris 2012-04-17 19:26:00

+0

需要修復return語句和函數簽名, – Mat 2012-04-17 19:27:08

+0

不應該是'rownames [i] = malloc ...'嗎? – 2012-04-17 19:29:03

回答

0

你有幾件事會在這裏。

函數聲明/原型需要有固定尺寸的陣列&矩陣。*

char *getRownames (int a, int b, char *matrix[a][b])

將不能工作,因爲編譯器不知道ab編譯程序時。如果你知道數組將是它的大小將需要

char *getRownames (int a, int b, char *matrix[7000][14])

。那麼你根本不需要ab。如果您希望能夠將不同大小的矩陣傳遞給函數,那完全是另一回事。

*(請注意,編譯器允許你離開了數組的第一個維度:char *matrix[][14]char *array[]

接下來,你需要通過malloc將返回值轉換爲char *,爲的malloc()返回void *:

rownames[a] = (char*)malloc(strlen(matrix[i][0])+1);

順便說一句,它應該是在循環rownames[i]。 :-)由於i是你的循環變量。

最後,它看起來像你想返回一個char *數組,但是return *rownames將只返回數組中的第一個值。同樣,如果你知道數組的大小,將現有的數組傳遞給函數並使其填入數值會更容易。否則,你必須malloc數組返回。

char *result[7000][14]; 
char *firstRows[7000]; 
//... other code that fills in these values 
getRownames(7000, 14, result, firstRows); 

void getRownames (int a, int b, char* matrix[7000][14], char* returnrows[7000]) 
{ 
    for(int i=0;i<a;i++){ 
     returnrows[i] = (char*)malloc(strlen(matrix[i][0])+1); 
     strcpy(returnrows[i],matrix[i][0]); 
    } 
} 
1

有幾個問題在這裏

  • 你的回報說法是錯誤的(這應該只是rownames,不* rownames)。無論如何,我不會這樣做。
  • 我沒有看到你的代碼的其餘部分,但是如果你沒有初始化*result[][0],你很可能會在strlen調用上發生段錯誤。
  • 我會避免試圖返回一個指向該大小的堆棧上的數組的指針(不要返回指向未被malloc'd的局部變量的指針),所以我會傳入數組並將函數fill它適合你。如果你有一個指向這個數據大小的指針,例如char *rownames=malloc(a*sizeof(char *));,你會沒事的。

所以我做了這個與我的測試代碼:

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

void getRownames (int a, int b, char *matrix[a][b], char* rownames[a]) 
{ 
    int i; 
    for(i=0;i<a;i++){ 
     //printf("%d\n",strlen(matrix[i][0])); 
     rownames[i] = malloc(strlen(matrix[i][0])+1); 
     strcpy(rownames[i],matrix[i][0]); 
    } 
    //strlen(matrix[i][0]) 
    //return &rownames[0]; 
} 

int main(void) { 
    char *result [700][14]; 
    int i=0; 
    for(i=0;i<700;i++){ 
    result[i][0]="abcd0"; 
    } 
    char *rownames[700]; 
    getRownames(700,14,result,rownames); 
    printf("I finished"); 
    printf("%s",rownames[0]); 
    printf("%s",rownames[1]); 
    printf("%s",rownames[2]); 
    printf("%s",rownames[3]); 
}