从void返回后,Int变量神秘地改变了值

时间:2017-10-28 18:47:05

标签: c arrays pointers ansi

我试图使二维动态字符串数组取得一些成功,但由于某种原因,两个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 个答案:

答案 0 :(得分:1)

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等常用函数名作为函数名。