c function returns an array of strings, char [], and the difference between the conversion char * (detail)

One reason, character pointer can be returned, as a character array of local variables can not be directly returned

More detailed reference blog: C function returns an array of strings

Put a piece of code direct comparison:

char * fork_user_name()
{
    char name[] = "veryitman";//!警告
    //!不应该返回一个局部变量 name 的地址(函数内部的变量在栈内存上)。
    return name;
}

char * fork_user_name2()
{
    char *name = "veryitman";
    return name;
}

int main()
{
    printf("fork_user_name: %s\n", fork_user_name());
    printf("fork_user_name2: %s\n", fork_user_name2());
    
    return 0;
}

result:

fork_user_name: (null)
fork_user_name2: veryitman

Conclusion: The local variables in the function as long as return is similar to int [],, are not the right thing to char [], long [] addresses.

Second, how to return the character array of local variables

1, the use of static

In the C language, with static define external variables and functions , in addition to the external file to the variable or function is located outside the visible, other files are inaccessible. The statement by static internal variable, the variable is a particular function of local variables can only be used in the function. static is a type of internal variables can only use a particular function, but has been dominated by variable storage space .

So using static modified look, there is no problem. Examples are as follows:

char * v_string()
{
    static char rest[10] = {'\0'};
    return rest;
}

2, using malloc

This way we can solve this problem, because the use of malloc memory is allocated on the heap rather than the stack memory above. But remember to use the free application for the release of the memory space in the caller, or likely to cause a memory leak.

Specific can look Shuangsushuangfei malloc and free in this article.

char * v_string()
{
    char *p = (char *)malloc(10 * sizeof(char));
    p = "\0";
    return p;
}

3, global variables

This program will make this method is not cohesive package, because it depends on a global variable.

char g_rest[100];
char * v_string()
{
    strcpy(g_rest, "verytiamn");
    return g_rest;
}

4, return pointer variable parameter

char * v_string(char *s1, char *s2)
{
    char *tmp = s1;
    // 省略...
    return tmp;
}

Third, the difference between an array of characters and character pointers

Transfer from paragraph: https://blog.csdn.net/u012611878/article/details/78291036

Same point

First Both types can correspond to a string, such as:

char * a=”string1”;
char b[]=”string2”;
printf(“a=%s, b=%s”, a, b);

Wherein a is a pointer to char variable , b is a char array (character array),

Secondly, many times both can be mixed , as a function of the time of transmission parameters, the argument may be a char *, parameter may be char [], such as:

void fun1(char b[]){
printf("%s",b);
}
int main(){
char *a="HellowWorld";
fun1(a);
}

In turn, the argument may be char [], char * parameter may be also possible.
There is reasonable, char * and char [] is definitely a different nature.

difference

1. char * is a variable, the value may be changed, char [] is a constant, the value can not be changed.
such as:

char * a="string1";
char b[]="string2";
a=b; //OK
a="string3"; //OK
b=a; //报错!左边操作数只读
b="string3"; //报错!左边操作数只读

Explain: a char type is a pointer variable, which value (points) may be varied; B is the name of an array of char, is the first address of the array element is constant and its value can not be changed.

2. char [] corresponding to the memory area can be always written, char * point to a region sometimes written, sometimes read-only
for example:

char * a="string1";
char b[]="string2";
gets(a); //试图将读入的字符串保存到a指向的区域,运行崩溃!
gets(b) //OK

Explain: a point to a string constant, i.e., a read-only memory point; he always point B represents a position in the memory array can always be written !

Note that if this change gets (a) on the legality:

char * a="string1";
char b[]="string2";
a=b; //a,b指向同一个区域,注意这里改变了a的指向
gets(a) //OK
printf("%s",b) //会出现gets(a)时输入的结果

Explanation: The value of a character array into a first address, namely & b [0], this address points to the area is char * or
char [8], said on the customary type of an array of characters, in fact, it can also be called "string variable" readable and writable area.

Note: char * itself is a character pointer variable , but both can point to a string constant, and can point to a string variable, the type of point determines the corresponding string can not be changed.

3.char * and char [] initialization operations fundamentally different:

char *a="Hello World";
char b[]="Hello World";
printf("%s, %d\n","Hello World", "Hello World");
printf("%s, %d %d\n", a, a, &a);
printf("%s, %d %d\n", b, b, &b);

Here Insert Picture Description
Visible results: Although corresponds to the same string, but the same "Hellow World" address and a corresponding address, the address pointed to by b are quite different; a &, & b are in the same memory area, and & bb
according to c zoning knowledge memory, we know that local variables are created in the stack area, and constants are created in the text constant area, obviously, variables a, b are the stack area, but a point constants (string constants) , b points to a variable (character array), pointing to his own (& b
b==&b[0])。

Description of the following issues:

  • char * a = "string1"; three operations is achieved:

1. Declare a char * variable (that is, declare a pointer to char variables).
2 opens up a space to store string constant "string1" in memory of a literal constant region. 3 The return address of the region, as the value assigned to the character variable is a pointer to
the final result: a pointer variable that points to a string constant "string1" (Note that if this time we then execute: char *
c = "string1 "; then, c == a, in fact, only the above steps 1 and 3, since the constant has been created in memory)

  • char b [] = "string2"; is the realization of two operations:

1. Declare a char array, the array 2 for the "assignment", is about "string2" of each character are assigned to each element of the array, it is stored on the stack.
The end result: "an array of values" (the value b is not noted) is equal to "string2", instead of pointing to a string constant b

PS:
Actually, char * a = "string1" ; the wording is not standard!
That is because a point to character constants, once strcpy (a, "string2") on the bad, trying to write to read-only memory area, the program will crash! Although the compiler will not warn under VS, but if you use the C compiler under the strict grammar of Linux GCC, MinGW compiler or use in the windows will get a warning.

So, we should follow the principle of "same type assignment" to write code:

const char * a=”string1”;

Ensure accident assignment will not compile.

summary

for

const char * a="string1"
char b[]="string2";

Const char type is 1.a, b is char const type (or understood as (const char) XX and char (const xx))

2.a is a pointer variable , a value (point) is can be changed , but only a point (string) constants, content area pointed immutable;

3.b is a pointer constant , b values (points) can not be changed ; but the target point b (array contents in the memory area b) is variable in

4. As a function of the parameter declaration time, char [] is handled as a char *! Two kinds of parameter declarations written entirely equivalent !

Fourth, character arrays and character pointers conversion

char [] char * rpm

It can be assigned directly, for example:

int main()
{
	char c_str_array[] = "veryitman.com";
    char *p_str;
    p_str = c_str_array;
    printf("p_str: %s\n", p_str);
	return 0;
}

char * transferred char []

That can not be directly transferred, the above may be used strnpy :

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{
    char c_str_array[] = "veryitman.com";
    char *p_str = "veryitman.com";
    strncpy(c_str_array, p_str, strlen(p_str));
    //strncpy把源字符串的字符复制到目标数组。然而,它总是正好向dst写入len个字符。如果strlen(src)的值小于len,dst数组就用额外的NUL字节填充到len长度,如果strlen(src)的值大于或等于len,那么只有len个字符被复制到dst中
    printf("c_str_array: %s\n", c_str_array);
    return 0
}

PS: strncpy does not copy the string \ 0 character, while strcpy was copied. This shows, for copying the character strncpy born, and a copy string strcpy born. But both are not out of bounds copy.

Detailed strnpy see: in-depth understanding of the function strncpy
stop the bullying: Please do not use strcpy, but with strncpy

Published 54 original articles · won praise 26 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_43629813/article/details/103498018