2014-10-02 53 views
0

我想在C语言中获得一个char *矩阵,但运行时错误发生在我身上。以下代码显示了我如何尝试这样做。谁能告诉我我错在哪里,为什么?我是C编程新手,但我来自Java和PHP世界。 预先感谢您有兴趣,并帮助我如何获得char *矩阵?

int rows = 10; 
int cols = 3; 

//I create rows 
char *** result = calloc(rows, sizeof(char **)); 

//I create cols 
for (int i = 0; i < cols; i++) 
{ 
    result[i] = calloc(cols, sizeof(char *)); 
} 

//Load values into the matrix 
for (int i = 0; i < rows; i++) 
{ 
    for (int j = 0; j < cols; j++) 
    { 
     result[i][j] = (char *)malloc(100 * sizeof(char)); 
     if (NULL != result[i][j]) 
     { 
      strcpy(result[i][j], "hello"); 
     } 
    } 
    printf("\n"); 
} 

//Print the matrix 
for (int i = 0; i < rows; i++) 
{ 
    for (int j = 0; j < cols; j++) 
    { 
     printf("%s\t", result[i][j]); 
    } 
    printf("\n"); 
} 

PS:我使用的Xcode与C99

运行时错误发生在这里:

result[i][j] = (char *)malloc(100 * sizeof(char)); 

的Xcode returs我EXC_BAD_ACCESS

+0

您将'result'初始化为10个char **元素的数组。然后你用'char *'指针填充这个数组的前3个元素,剩下的7个设置为零。您的运行时错误发生在下面的嵌套循环中,在这里您取消引用所有这些空指针并尝试在其中存储文本字符串。 – 2014-10-02 20:27:13

+0

你说得对,@squeamishossifrage。我颠倒了这个概念。我很感谢你。现在所有的工作。 – 2014-10-02 20:35:20

回答

1

此:

for (int i = 0; i < cols; i++) 
{ 
    result[i] = calloc(cols, sizeof(char *)); 
} 

应该是这样的:

// -----------------here 
for (int i = 0; i < rows; i++) 
{ 
    result[i] = calloc(cols, sizeof(char *)); 
} 

无关:Stop casting memory allocation functions in C。这:

result[i][j] = (char*)malloc(100 * sizeof(char)); 

应该仅仅是这样的:

result[i][j] = malloc(100 * sizeof(char)); 

我觉得很奇怪,这是在这里,因为你没有正确不calloc结果。


替代版本:可变长度的数组(VLA)

您可以通过利用VLAS如果你的平台支持它们切出你的分配环中的一个。如果完成,代码将减少到分配char*的整个矩阵与一个单一的calloc。例如:

int main() 
{ 
    int rows = 10; 
    int cols = 3; 

    // create rows 
    char *(*result)[cols] = calloc(rows, sizeof(*result)); 

    // load values into the matrix 
    for (int i = 0; i < rows; i++) 
    { 
     for (int j = 0; j < cols; j++) 
     { 
      result[i][j] = malloc(100 * sizeof(char)); 
      if (NULL != result[i][j]) 
      { 
       strcpy(result[i][j], "hello"); 
      } 
     } 
     printf("\n"); 
    } 

    //Print the matrix 
    for (int i = 0; i < rows; i++) 
    { 
     for (int j = 0; j < cols; j++) 
     { 
      printf("%s\t", result[i][j]); 
     } 
     printf("\n"); 
    } 
} 
+0

我试过你的解决方案和所有的工作。正如我对@squeamishossifrage所说的,我颠倒了这个概念。我非常感谢你。祝你有个愉快的夜晚:)) – 2014-10-02 20:37:40

0

在第一个for循环中,您只为3行分配内存,并且您试图访问最后一个循环中的3行以上。