[英]c: implementation of a rownames function
我有一个二维数组(指向字符串)
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并且必须分配自己的内存。
这里有几个问题
*result[][0]
,很可能在strlen调用中出现段错误。 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]);
}
您正在这里进行几件事。
函数声明/原型的数组和矩阵的大小必须固定。*
char *getRownames (int a, int b, char *matrix[a][b])
将不起作用,因为编译器在编译程序时不知道a
或b
。 它需要是
char *getRownames (int a, int b, char *matrix[7000][14])
如果您知道数组将是该大小。 然后,您根本不需要a
或b
。 如果您希望能够将大小不同的矩阵传递给函数,则完全是另一回事。
*(请注意,编译器允许您省略数组的第一维: char *matrix[][14]
或char *array[]
)
接下来,您需要将返回值从malloc强制转换为char *,因为malloc()返回void *:
rownames[a] = (char*)malloc(strlen(matrix[i][0])+1);
顺便说一句,它应该是循环中的行名rownames[i]
。 :-)因为i
是你的循环变量。
最后,看起来您想返回一个char *数组,但是return *rownames
只会发送回数组中的第一个值。 同样,如果您知道数组的大小,则将现有数组传递给函数并使其填充值会更容易。 否则,您必须分配该数组以返回。
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]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.