【发布时间】:2016-05-20 13:04:38
【问题描述】:
我正在学习 C 并尝试创建一个可以创建字符串数组的函数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void parse(char ***aoa)
{
char *string = calloc(9, sizeof(char)); //create a string of size 8+1
strcpy(string, "hi world"); // put text in that array
char **array = calloc(10, sizeof(char *)); //create an array of strings
aoa = calloc(10, sizeof(char *)); //create and array of arrays
aoa[0] = array; //assign string array to the 0th elements of new array
array[0] = string; //assign our string to 0th element of string carry
printf("%s\n", aoa[0][0]); //print 0th element of 0th array.
}
int main()
{
char ***array = NULL;
parse(array);
printf("%s\n", array[0][0]);
return 1;
}
aoa(数组的数组)在堆上,所以这两种方法应该是一样的。它确实在解析函数中打印“hi world”,但在 main 中给出了 Segmentation Fault,我的代码有什么问题?
显然我需要 free() 一切并进行错误检查,但我删除了它以显示问题的要点
【问题讨论】:
-
是什么阻止您为 10x10 数组分配 100 并将其用作 10x10 数组?
-
我稍后会为选定的字符串数组动态重定位空间。
-
3x3 示例:最初看起来像这样:{{hi, my, name}, {one, two, three}, {red, green, blue}}。但稍后我可能需要将其更改为:{{hi, my, name, is, Alex}, {one, two}, {cyan, magenta, yellow, key}}
-
char **array 不是多维数组,this =>> char array[SIZE][SIZE] 是多维数组。
标签: c arrays pointers multidimensional-array segmentation-fault