简体   繁体   English

将字符串传递给C中的函数

[英]Pass a string to a function in C

I have the following code: 我有以下代码:

#include <stdio.h>

char * lookLine (FILE *fichero) 
{
    char p[25];
    fgets (p, sizeof (p), fichero);
    return p;
}

int main (void) {
    printf ("%s\n", lookLine (fopen ("suma.c", "r")));
    return 0;
}

And I get the following output: 我得到以下输出:

#��x�

Not nice. 不是很好。 My intention is to print out the first line of the file whose name "suma.c". 我的意图是打印出名称为“ suma.c”的文件的第一行。 It should print out the following: 它应该打印出以下内容:

#include <stdio.h>

Nevertheless, if I print out the content of p string into the same lookFile function, it does it fine: 不过,如果我将p字符串的内容打印到相同的lookFile函数中,就可以了:

#include <stdio.h>

void lookLine (FILE * fichero) 
{
    char p[25];
    fgets (p, sizeof (p), fichero);
    printf ("%s\n", p);
}

int main (void) {
    lookLine (fopen ("suma.c", "r"));
    return 0;
}

And the output I get now is the correct one: 我现在得到的输出是正确的:

#include <stdio.h>

My reasoning is this: by using fgets I save the string of the first line of "name.c" in the p array and I return its address, which is taken by the second argument of printf function in main . 我的理由是这样的:通过使用fgets我省“name.c”的第一行的字符串p数组和我返回它的地址,这是采取的第二个参数printf函数main
But I have found out that this only works when I use the printf function directly into the same lookLine function... 但是我发现这仅在我直接将printf函数用于同一个lookLine函数lookLine有效...

Please, could someone tell me what's really going on here? 拜托,有人可以告诉我这里的实际情况吗?

It's because you are returning a pointer to a local array from the read function. 这是因为您要从read函数返回一个指向本地数组的指针。

Remember that local variables are stored on the stack, and that includes arrays. 请记住,局部变量存储在堆栈中,其中包括数组。 And when the function returns that stack space is reclaimed by the compiler to be used by other function calls. 当函数返回时,编译器将回收堆栈空间,以供其他函数调用使用。 So you have a pointer pointing to another function's memory. 因此,您有一个指向另一个函数的内存的指针。

The lifetime of the array p ends at the return statement (technically p is a local variable with automatic storage duration; this means it's lifetime ends at the matching } ). 数组p的生存期在return语句处终止(从技术上讲, p是具有自动存储持续时间的局部变量;这意味着其生存期在匹配的}处结束)。

The program then invokes undefined behavior because it uses an indeterminate value (reading from a pointer that no longer points to valid memory). 该程序然后调用未定义的行为,因为它使用了不确定的值(从不再指向有效内存的指针读取)。 This is the reason you can print the string while still in read() , but get garbage when printing from main() . 这就是为什么您可以在仍处于read()打印字符串,但从main()打印时却得到垃圾的原因。

And note that read is a POSIX function that may be interfering with the one you defined (not a problem in a strict C89 or C99 mode, but most compilers aren't by default). 并请注意, read是一种POSIX函数,可能会干扰您定义的函数(在严格的C89或C99模式下不是问题,但默认情况下大多数编译器都不是)。 [The OP in the meantime renamed the function to lookLine() .] [与此同时,OP将函数重命名为lookLine() 。]

As pointed to by Joachin Pileborg correctly, you are trying to return a stack variable which will be reclaimed, when you return from the function. 正如Joachin Pileborg正确指出的那样,您试图返回一个从函数返回时将被回收的堆栈变量。

Instead you can try to pass a character array and it's size as inputs to the function read. 相反,您可以尝试将字符数组及其大小作为传递给函数read的输入。 Btw, if you don't intend to do anything else apart from calling fgets in the read function, then it is better that you call fgets in the main function itself. 顺便说一句,如果除了在read函数中调用fgets之外,您不打算做其他事情,那么最好在main函数本身中调用fgets。

Incase if you are doing some additional logic in read and you also cannot pass the buffer and it's size as input to read function, you can allocate the memory required from reading using malloc and return the pointer to the calling function. 如果您要在读取中执行一些其他逻辑,并且您也无法通过缓冲区并将缓冲区的大小作为读取函数的输入,则可以使用malloc分配读取所需的内存,并将指针返回到调用函数。 But, personally, I wouldn't recommend it as it is better to ensure the caller of the read takes the responsibility of creation and deletion of the array. 但是,就个人而言,我不建议这样做,因为最好确保read的调用者承担创建和删除数组的责任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM