C language string copy

Source: Internet
Author: User

The C language defines a string that can use pointers or arrays, such:
(1) char * s = "hello"; // "hello" isString constant,S is a pointer to a constant.Constants cannot be changed. They cannot be written as s [0] = X, but they can be changed to point to different constants, such as S = "Xeon ";
(2) Char s [] = "hello ";//Pointer constant. The value of s cannot be modified.But you can modify the content to which it points, s [0] = x
The difference between the two is:
(1) The defined string is inProgramCannot be modified because it is stored inCodeSegment;
(2) The defined string can be modified and stored in the data segment or stack.

The two string-defining methods are slightly different inside and outside the function.

* Function External:
(1) char * s = "hello";/* defines the pointer S (Data Segment) and constant string "hello" (Data Segment). The value of S is the first address of the string */
(2) Char s [] = "hello";/* defines the character array S, and the array content is "hello" (code segment ), note that S is only a symbol, not a variable entity */

* Internal function:
If (1) and (2) are used internally in the function, the "hello" string is stored in the code segment. When the function is called,
(1) only assign the first address of the string "hello" to S
(2) copy the string "hello" to the stack and assign the first address of the copy string to S.

Therefore, the content referred to by S in (1) cannot be changed, and the string referred to by S in (2) can be modified. s points to the copy of the "hello" string and does not affect the original string, each time a function is called, it is copied once.

Note: The use of (1) (2) in the function is not modified with the static keyword. If the static keyword is added, it is no different from the external function.
******************************
(1) The "hello" string can be modified with a slight change
Char * s = (char []) {"hello"}; // It seems to be unavailable
The anonymous "hello" string is stored in the data segment.
You can also assign an anonymous array to an int pointer, for example:
Int * P = (INT [10]) {[0... 9] = 0 };

Bytes ----------------------------------------------------------------------------------------

Basic concepts and usage of malloc () and free:

1. function prototype and description:

Void * malloc (long numbytes): This function allocates numbytes bytes and returns a pointer to this memory. If the allocation fails, one is returned.

NULL pointer ).

There are many reasons for allocation failure, such as insufficient space.

Void free (void * firstbyte): This function returns the space previously allocated with malloc to the program or the operating system, that is, this memory is released,

Let it be free again.

2. Function usage:

In fact, these two functions are not very difficult to use, that is, after malloc () is used up, I think it is enough to give it free (). For example:
Program code:
// Code...
Char * PTR = NULL;
PTR = (char *) malloc (100 * sizeof (char ));
If (null = PTR)
{
Exit (1 );
}
Gets (PTR );

// Code...
Free (PTR );
PTR = NULL;
// Code.

 

The Code is as follows:
# Include <stdio. h>
Void str_copy (char * From, char * );
Main ()
{Char * A = "I am Chinese! ";
Char AA [20] = "sssssssssssssssssssss ";
Char * B;
B = AA;
Str_copy (A, B );
Printf ("after string copy: \ n ");
Printf ("% s", AA); // or printf ("% s", B); all succeed !!
Printf ("\ n ");
}
Void str_copy (char * From, char *)
{
While (* To ++ = * From ++ );

}
But I changed the code, but a segment error occurred:
# Include <stdio. h>
Void str_copy (char * From, char * );
Main ()
{Char * A = "I am Chinese! "; // You can assign values directly to pointer variables. ThenThe String constant created during pointer Initialization is defined as read-only. That is, the content of * A cannot be changed.
Char * B = "ssssssssssssssssssssssss "; // You can assign values directly to pointer variables. ThenThe String constant created during pointer Initialization is defined as read-only. That is, the content of * B cannot be changed.
Str_copy (A, B );
Printf ("after string copy: \ n ");
Printf ("% s", B );
Printf ("\ n ");
}
Void str_copy (char * From, char *)
{
While (* To ++ = * From ++ );

}

The so-called segment error isGenerally, the pointer is not assigned a value.Is the so-calledWild pointerBut this char * B = "ssssssssssssssssssssss"; does the string definition assign B an address pointing to an array? Why is this happening?

 

# include "stdafx. H "
char * strcpy_v1 (char * DEST, const char * SRC)
{< br> // Use assertions during debugging, entry detection
assert (DEST! = NULL) & (SRC! = NULL);
// note that the memory here points to the memory where the Dest parameter is located, not the stack memory, therefore, you can return
char * To = DEST;
// The main operation is completed in the while condition
while (* DEST ++ = * SRC ++ )! = '\ 0') // determines whether the value is' \ 0'
{< br> NULL;
}< br>
// return the first address of the copy string to facilitate concatenation, for example, strlen (strcpy (DEST, "hello")
return;
}

/*
* Description: String Copy version 2
* Parameter: DEST target address, SRC Source Address
* Return: the copied address is returned. If an error occurs, it is not defined.
* Exception: string overflow may occur, and the space occupied by DEST is not as large as that occupied by Src.
*/
Char * strcpy_v2 (char * DEST, const char * SRC)
{
Char * D = DEST;
Char C;

While (C = * SRC ++ )! = '\ 0 ')
{
* (DEST ++) = C;
}

* DEST = '\ 0 ';

Return D;
}

/*
* Note: Copy string Version 2 (can you find out the cause of the error)
* Parameter: DEST target address, SRC Source Address
* Return: the copied address is returned. If an error occurs, it is not defined.
* Exception: string overflow may occur, and the space occupied by DEST is not as large as that occupied by Src.
*/

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.