[英]C changing a pointer in a function
I want to write a function that processes a string that looks like this: 我想编写一个处理如下字符串的函数:
|1,2,3,4|(1->2),(2->3),(3->1)|
| 1,2,3,4 |(1-> 2),(2-> 3),(3-> 1)|
The result should be a breaking down of the string into these strings: 结果应该是将字符串分解为以下字符串:
- 1
1
- 2
2
- 3
3
- 4
4
- (1->2)
(1-> 2)
- (2->3)
(2-> 3)
- (3->2)
(3-> 2)
This is my code: 这是我的代码:
int processPart(char*** dest, char* from) //Processes a half at a time
{
int len = 0;
char* cutout = strtok(from, ",");
while(cutout)
{
(*dest) = (char**)realloc(dest, (len + 1) * sizeof(char*)); <<<<<<<
(*dest)[len] = (char*)calloc(strlen(cutout) + 1, sizeof(char));
memcpy((*dest)[len], cutout, strlen(cutout));
cutout = strtok(NULL, ",");
len++;
}
return len;
}
void processInput(char*** vertices, char*** edges, char* input, int* sizev, int* sizee)
{
int vlen = 0, elen = 0;
char* string = input + 1;
char* raw_vertices;
char* raw_edges;
string[strlen(string)] = '\0';
raw_vertices = strtok(string, "|");
raw_edges = strtok(NULL, "|");
*sizev = processPart(vertices, raw_vertices); //First the vertices
*sizee = processPart(edges, raw_edges); //Then the edges
}
int main()
{
char* in = stInput(); //input function
char** c = NULL, **b = NULL;
int a, d, i;
processInput(&c, &b, in, &a, &d);
for(i = 0; i < a; i++)
{
printf("%s\n", c[i]);
}
printf("++++++++++++++++");
for(i = 0; i < d; i++)
{
printf("%s\n", b[i]);
}
return 0;
}
However, I get a corruption of the heap at the line marked by <<<<<<< 但是,在<<<<<<<
Anyone knows what my mistake is? 有人知道我的错误是什么吗?
In the erroneous line 在错误的行中
(*dest) = (char**)realloc(dest, (len + 1) * sizeof(char*));
a *
is missing before the dest
argument. dest
参数前缺少*
。 You could have spotted this easier if you hadn't cluttered the expression with the useless cast. 如果您不使用无用的转换来使表达混乱,那么您可能会发现这更容易。 I'd write
我会写
*dest = realloc(*dest, (len + 1) * sizeof**dest);
- that way we can see better the matching of first argument and left operand of the assignment. -这样,我们可以更好地看到赋值的第一个参数与左操作数的匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.