C语言 Int变量在从void返回后神秘地改变了值

fnatzsnv  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(120)

我试图做二维动态字符串数组,并取得了一些成功,但由于某种原因,两个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;
}
zzlelutf

zzlelutf1#

拜托了
1)使用warning和READ THE MESSAGES选项编译代码

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

相关问题