在C中传递多维数组 [英] Passing multi-dimensional arrays in C
本文介绍了在C中传递多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试学习C,我遇到了一个我无法解决的问题。 b
#include< stdio.h>
#include< stdlib.h>
#include< string.h>
#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); (i = 0; i< size; ++ i){
printf(%s\\\
,array [i]);
}
return 0;
}
我不知道为什么上面的内容无法读回数组的内容创建它之后我已经花了一个小时试图理解为什么它失败,但空手而归。毫无疑问,这是微不足道的。
干杯,
解决方案
工作代码:
#include< stdio.h>
#include< stdlib.h>
#include< string.h>
#define ELEMENTS 5
void make(char *** array){
char * t =Hello,World!
* array = malloc(ELEMENTS * sizeof(char *));
int i; (i = 0; i< ELEMENTS; ++ i)
{
(* array)[i] = strdup(t);
}
}
int main(int argc,char ** argv){
char ** array;
make(& array);
int i; (i = 0; i< ELEMENTS; ++ i)
{
printf(%s\\\
,array [i]);
free(array [i]);
}
free(array);
return 0;
}
由于其他已发布 - 有未使用的大小,strdup分配内存本身,然后释放内存是很好的...
I am currently trying to learn C and I have come to a problem that I've been unable to solve.
Consider:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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,
解决方案
Here is the working code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 5
void make(char ***array) {
char *t = "Hello, World!";
*array = malloc(ELEMENTS * sizeof(char *));
int i;
for (i = 0; i < ELEMENTS; ++i) {
(*array)[i] = strdup(t);
}
}
int main(int argc, char **argv) {
char **array;
make(&array);
int i;
for (i = 0; i < ELEMENTS; ++i) {
printf("%s\n", array[i]);
free(array[i]);
}
free(array);
return 0;
}
As the other have posted - there was unused size, and strdup allocates memory by itself, and it is nice to free the memory afterwards...
这篇关于在C中传递多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文