c:实现rownames函数

时间:2012-04-17 19:04:05

标签: c multidimensional-array strcpy slice

我有一个2d指针数组(到字符串)

 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并且必须分配我自己的记忆。

2 个答案:

答案 0 :(得分:1)

这里有几个问题

  • 你的return语句是错误的(它应该是rownames,而不是* rownames)。反正我也不会这样做。
  • 我没有看到你的其他代码,但如果你没有初始化*result[][0],你很可能会在strlen调用上发生段错误。
  • 我会避免尝试返回指向该大小的堆栈上的数组的指针(不要返回指向没有malloc的局部变量的指针),所以我会传入数组并让函数填充它出来给你。如果你有malloc指向那个数据大小的指针,即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]);
}

答案 1 :(得分: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]);
     }
}