二维数组,在C使用释放calloc [英] 2d array, using calloc in C
问题描述
我试图创建字符的二维数组字符的存储产品线。例如:
行[0] =你好;
行[1] =你的背;
行[2] =再见;
由于线路必须是动态的,因为我不知道我有多少行需要在第一。这里是code我有:
INT I;
焦炭**行=(字符**)释放calloc(大小,sizeof的(字符*));对于(i = 0; I<大小;我++){
线[I] =(字符*)释放calloc(200的sizeof(字符));
}对于(i = 0; I<大小;我++){
免费(行[I]);
}免费(线);
我知道,每行不能去超过200个字符。我不断收到这样的错误错误C2059:语法错误:'对'和这样的。什么我做错了任何想法?
没有在code不是一个函数。
块引用>您不能只是把任意语句的C和C ++函数之外。你虽然可以做的是使用一个函数来初始化变量:
的char ** init_lines(){
焦炭** LN = / * ... * /;
//你的分配等等。在这里
返回LN;
}焦炭**线= init_lines();I'm trying to create a 2D array of chars to storage lines of chars. For Example:
lines[0]="Hello"; lines[1]="Your Back"; lines[2]="Bye";
Since lines has to be dynamically cause i don't know how many lines i need at first. Here is the code i have:
int i; char **lines= (char**) calloc(size, sizeof(char*)); for ( i = 0; i < size; i++ ){ lines[i] = (char*) calloc(200, sizeof(char)); } for ( i = 0; i < size; i++ ){ free(lines[i]); } free(lines);
I know that each line can't go over 200 chars. I keep getting errors like "error C2059: syntax error : 'for'" and such. Any ideas of what i did wrong?
解决方案No the code is not in a function.
You can't just put arbitrary statements outside of functions in C and C++. What you can do though is use a function to initialize the variable:
char** init_lines() { char** ln = /* ... */; // your allocations etc. here return ln; } char** lines = init_lines();
这篇关于二维数组,在C使用释放calloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!