Passing multi-dimensional arrays in C

I am currently trying to learn C and I have come to a problem that I've been unable to solve. Consider: #include #include #include #define ELEMENTS 5 void make(char **array, int *array_size) { int i; char *t = "Hello, World!"; array = malloc(ELEMENTS * sizeof(char *)); for (i = 0; i < ELEMENTS; ++i) { array[i] = malloc(strlen(t) + 1 * sizeof(char)); array[i] = strdup(t); } } int main(int argc, char **argv) { char **array; int size; int i; make(array, &size); for (i = 0; i < size; ++i) { printf("%s\n", array[i]); } return 0; } I have no idea why the above fails to read back the contents of the array after creating it. I have literally spent an hour trying to understand why it fails but have come up empty handed. No doubt it's something trivial. Cheers,
Technically, what you have are not "multi-dimensional arrays". You have an array of pointers, each of which points to the beginning of a smaller-dimension array. "Multi-dimensional array" refers to something different, with all the memory allocated contiguously.

以上就是Passing multi-dimensional arrays in C的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏