我遇到了这个问题。基本上我想将整数字符串解析为 int**,其中子 int 数组有两个长。第一个索引是数字,第二个索引是与数字相关的十的幂。
例如 12345 将给出 [[1, 4], [2, 3], [3, 2], [4, 1], [5, 0]]
这是代码:
#include <stdlib.h>
int ft_strlen(char *str)
{
int count;
count = 0;
while (*str++)
count++;
return (count);
}
int **parray(char *str)
{
int **ret;
int len;
int i;
len = ft_strlen(str);
ret = (int **)malloc(sizeof(int) * len);
if (ret == NULL)
return (NULL);
i = 0;
while (i < len)
{
ret[i] = (int *)malloc(sizeof(int) * 2);
if (ret[i] == NULL)
return (NULL);
ret[i][0] = str[i] - '0';
ret[i][1] = len - 1 - i;
i++;
}
return (ret);
}
然后在主函数中进行测试,如下所示:
#include <stdio.h>
int main()
{
char *str = "1255555555555555";
int**ret = parray(str);
int i = 0;
while (i < ft_strlen(str))
{
printf("%d ", ret[i][0]);
printf("%d ", ret[i][1]);
printf("\n");
i++;
}
}
由于某种原因打印出来:
29791280 0
29791408 0
5 13
5 12
5 11
5 10
5 9
5 8
5 7
5 6
5 5
5 4
5 3
5 2
5 1
5 0
请注意,该程序对于小于或等于 4 位数字的字符串可以正常工作。当您再次运行程序时,前两个非工作值也总是会发生变化。我假设某处有溢出,但我不知道在哪里,也不知道如何溢出。我对 c 相当陌生,所以如果这是一个愚蠢的错误,请原谅我。
ret = (int **)malloc(sizeof(int) * len);
错了。 ret
的类型是 int **
。它是一个指向 int *
的指针。您正在为 int *
分配空间。所以你想要 int *
的大小。
通常,最好根据您分配给的事物来计算大小:
ret = malloc(len * sizeof *ret);`
*ret
是 ret
将指向的样本,因此 sizeof *ret
是其中一个事物的大小。在这种情况下,它将是 int *
的大小。此表单会自动将分配大小调整为 ret
的任何类型。例如,如果您稍后在处理程序时更改 ret
的声明,则此处的大小将自动正确,无需再次编辑。
另外,不要在 C 中转换
malloc
的返回值。(C++ 不同。)没有必要,并且它可以掩盖声明 malloc
的失败(因为意外地省略了标头的包含) ).