我正在尝试使二维动态字符串数组取得一些成功,但是由于某些原因,两个int变量(实际上是行数(指针数组)和字符串的大小(它们可以有多长时间))发生变化达到神秘的价值。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
void write (char ***p, int size_r, int size_c)
{
int i;
for (i = 0; i < size_r; i++)
{
printf("%s", p[i]);
}
return;
}
void arr_of_p (char*** p, int size_r, int size_c)
{
int i;
for (i = 0; i < size_r; i++)
{
p[i] = "helo\n";
}
return;
}
int main(void)
{
int string_n; printf("How many strings: "); scanf("%d", &string_n);
int string_l; printf("How long are the strings: "); scanf("%d", &string_l);
char **s_p = (char**) malloc(string_n*sizeof(char*));
int i;
for (i = 0; i < string_n; i++)
{
s_p[i] = (char*) malloc(string_l*sizeof(char));
}
arr_of_p(&s_p, string_n, string_l);
printf("%d\n%d\n", string_n, string_l); // for debugging purpose, add breakpoint here.
//"string_n" and "string_l" will be identical to the value of "i" in "arr_of_p()" for some reason...
write(&s_p, string_n, string_l);
return 0;
}
最佳答案
请
1)使用警告选项编译代码,然后阅读消息
t.c: In function ‘write’:
t.c:11:18: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat=]
printf("%s", p[i]);
^
t.c:6:40: warning: unused parameter ‘size_c’ [-Wunused-parameter]
void write (char ***p, int size_r, int size_c)
^~~~~~
t.c: In function ‘arr_of_p’:
t.c:21:14: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
p[i] = "helo\n";
^
t.c:16:43: warning: unused parameter ‘size_c’ [-Wunused-parameter]
void arr_of_p (char*** p, int size_r, int size_c)
^~~~~~
2)提供似乎有问题的明确示例。
3)避免使用常见的函数名称,例如
write
作为函数名称。