简体   繁体   English

使用C返回“字符串”时的奇怪行为

[英]Strange behavior when returning “string” with C

I'm a noob to C and I found my program acting very weird: 我是C语言的菜鸟,我发现我的程序表现得很奇怪:

Here's the code: 这是代码:

#include <stdbool.h>
#include <string.h>
#include <conio.h>
#include <stdio.h>

char * p(char arg[] , char sym[] , int i , bool rv) {
    char head[i],w[i];
    strncpy(head,arg,i); head[i] = "\0";
    int l;
    for (l = 0 ; l <= (int)(strlen(sym) / i) ; l++) {
        strncpy(w,sym+l*i,i); w[i] = "\0";
        if (strcmp(head,w) == 0) {
            if (rv) { return head; } else {
                char v[strlen(arg) - i];
                strcpy(v,arg+i);
                v[strlen(arg)-i] = "\0";
                return v;
            };
        };
    };
    return arg;
}

int main() {
    printf(p("/parameter","+-\\/",1,false));
    getch();
}

The MAIN problem is that the returning value of the function is either a "string" of randomly generated codes or simply nothing. 主要的问题是该函数的返回值是随机生成的代码的“字符串”,或者仅仅是什么。

It was expected to return / for return h; 预期返回/对于return h; and parameter for return v; return v; parameter return v; .

The other problem is that there is NO error found when I compile the program but bunch of warnings telling that the function returns address of local variable and assignment makes integer from pointer without a cast . 另一个问题是,在编译程序时没有发现错误,但是一堆警告告诉该function returns address of local variable并且assignment makes integer from pointer without a cast

In the other hand, return arg; 另一方面, return arg; in very peaceful and doesn't gives out any error. 非常和平,不会发出任何错误。 (Try to change my codes in p("/parameter","+-\\\\/",1,false) if you don't believe it.) What have I done wrong? (如果您不相信,请尝试更改p("/parameter","+-\\\\/",1,false) 。)我做错了什么?


Usage of the function: 功能用法:

p(" argument_passed_to_check "," symbols_accepted to_be_at_the_front ","separate_for_each_ i _characters","return_header_instead_of_parameter") p(“ arguments_passed_to_check ”,“ symbol_to_be_at_the_front ”,“ separate_for_each_ i _characters”,“ return_header_instead_of_parameter”)

expected result: 预期结果:

p("-argue","/\\\\-",1,false) returns argue p("-argue","/\\\\-",1,false)返回argue

p("/help","me",1,false) returns /help p("/help","me",1,false)返回/help

p("/help","me",1,true) returns (null) p("/help","me",1,true)返回(null)

p("--parameter","--++",2,false) returns parameter p("--parameter","--++",2,false)返回parameter

p("--parameter","--++",2,true) returns -- p("--parameter","--++",2,true)返回--


Summary for what am I asking help for: 我需要帮助的摘要:

  • Except for return arg , other returning parts is weird: return head; 除了return arg ,其他返回部分都很奇怪: return head; is giving out random characters ; 散发出随机的字符; return v; returns nothing at all. 完全不返回任何内容。 How can I let them work as the expected results? 如何让它们按预期效果工作?

  • Why are there those warnings? 为什么会有这些警告?

  1. Since head is defined as char head[i] , its last element is head[i-1] . 由于head被定义为char head[i] ,因此它的最后一个元素是head[i-1] Attempting to access head[i] has behavior not defined by the C standard. 尝试访问head[i]具有C标准未定义的行为。

  2. Since w is defined as char w[i] , its last element is w[i-1] . 由于w被定义为char w[i] ,因此它的最后一个元素是w[i-1] Attempting to access w[i] has behavior not defined by the C standard. 尝试访问w[i]具有C标准未定义的行为。

  3. Since v is defined as char v[strlen(arg) - i] , its last element is v[strlen(arg) - i - 1] . 由于v被定义为char v[strlen(arg) - i] ,所以它的最后一个元素是v[strlen(arg) - i - 1] Attempting to access v[strlen(arg) - 1] has behavior not defined by the C standard. 尝试访问v[strlen(arg) - 1]具有C标准未定义的行为。

  4. Since w is defined inside a brace-enclosed block of statements without extern or static , it is has automatic storage duration associated with the block, so it exists only while the function is block. 由于w是在不带externstatic的大括号括起来的语句块内定义的,因此它具有与该块关联的自动存储持续时间,因此仅在该函数为block时才存在。 When the return statement is executed, w ceases to exist (in C's abstract machine). 当执行return语句时, w不再存在(在C的抽象机中)。 The statement return w; 语句return w; attempts to return a pointer to the first element of w (because, in this use, an array is automatically converted to a pointer to its first element). 尝试返回指向w的第一个元素的指针(因为在此用法中,数组会自动转换为指向其第一个元素的指针)。 When this return statement is executed, the pointer becomes invalid. 当执行该return语句时,指针变为无效。

  5. Since v is defined inside a brace-enclosed block of statements without extern or static , it has automatic storage duration associated with the block, so v exists only while the statement is executing. 由于v是在不带externstatic的大括号括起来的语句块内定义的,因此它具有与该块关联的自动存储持续时间,因此v仅在语句执行时才存在。 When return v; return v; is executed, execution of the block ends, and the returned pointer becomes invalid. 执行后,该块的执行结束,并且返回的指针变为无效。

  6. head[i] is a character, but "\\0" is a string containing one character, so head[i] = "\\0"; head[i]是一个字符,但是"\\0"是包含一个字符的字符串,因此head[i] = "\\0"; is an improper assignment. 是不适当的任务。 The string will be converted to a pointer to its first element, resulting in an attempt to assign a pointer to a char . 该字符串将被转换为指向其第一个元素的指针,从而导致尝试将指针分配给char This is a constraint violation, and your compiler should produce a warning for it. 这是一个约束违例,您的编译器应对此发出警告。 The same problem occurs in w[i] = "\\0"; w[i] = "\\0";时也会发生同样的问题w[i] = "\\0"; and v[strlen(arg)-i] = "\\0"; v[strlen(arg)-i] = "\\0"; . The proper code would be head[i] = '\\0'; 正确的代码应为head[i] = '\\0'; (once the size of head is fixed to include an element head[i] ). (一旦head大小固定为包括元素head[i] )。

Remedies include: 补救措施包括:

  • Define each array to be large enough for all the elements to be written into it. 将每个数组定义为足以将所有元素写入其中的数组。
  • To return strings created inside a function, either dynamically allocate space for them (as with malloc ), create the strings inside arrays provided by the caller, or use arrays with static storage duration. 要返回在函数内部创建的字符串,请为它们动态分配空间(如使用malloc ),在调用方提供的数组内创建字符串,或使用具有静态存储持续时间的数组。 If you use the first option, dynamically created arrays, you should make provisions for the space to be released (as by the caller passing them to free when done with them). 如果使用第一个选项,即动态创建的数组,则应为要释放的空间做好准备(例如,调用者在完成处理时将它们传递给free )。 You should avoid using arrays with static storage duration, as it has limited and troublesome use (such as the fact that only one such array exists for each definition, yet a function may be called multiple times by callers that each want their own separate data). 您应该避免使用具有静态存储持续时间的数组,因为它的使用有限且麻烦(例如,每个定义只存在一个这样的数组,而每个调用者可能想要多次调用一个函数,而每个调用者都想要自己的独立数据) 。

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

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