C语言内存和字符操作函数

C/C++对于其它语言的优势是运行快速和方便的内存操作。所以我总结了string.h里面常用的内存和字符操作函数

string.h

This header file defines several functions to manipulate C strings and arrays.

size_t

Unsigned integral type
Alias of one of the fundamental unsigned integer types.

It is a type able to represent the size of any object in bytes: size_t is the type returned by the sizeof operator and is widely used in the standard library to represent sizes and counts.

In , it is used as the type of the parameter num in the functions memchr, memcmp, memcpy, memmove, memset, strncat, strncmp, strncpy and strxfrm, which in all cases it is used to specify the maximum number of bytes or characters the function has to affect.

It is also used as the return type for strcspn, strlen, strspn and strxfrm to return sizes and lengths.

NULL

Null pointer
This macro expands to a null pointer constant.

C
A null-pointer constant is an integral constant expression that evaluates to zero (like 0 or 0L), or the cast of such value to type void* (like (void*)0).
C++98
A null-pointer constant is an integral constant expression that evaluates to zero (such as 0 or 0L).
C++11
A null-pointer constant is either an integral constant expression that evaluates to zero (such as 0 or 0L), or a value of type nullptr_t (such as nullptr).

A null pointer constant can be converted to any pointer type (or pointer-to-member type), which acquires a null pointer value. This is a special value that indicates that the pointer is not pointing to any object.

memcpy

void * memcpy ( void * destination, const void * source, size_t num );

Copy block of memory
Copies the values of num bytes from the location pointed to by source directly to the memory block pointed to by destination.

The underlying type of the objects pointed to by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.

The function does not check for any terminating null character in source - it always copies exactly num bytes.

To avoid overflows, the size of the arrays pointed to by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).
Parameters
destination
Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
source
Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
num
Number of bytes to copy.
size_t is an unsigned integral type.
Return Value
destination is returned.

memmove

void * memmove ( void * destination, const void * source, size_t num );

Move block of memory
Copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

The underlying type of the objects pointed by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.

The function does not check for any terminating null character in source - it always copies exactly num bytes.

To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes.

Parameters

destination
Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
source
Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
num
Number of bytes to copy.
size_t is an unsigned integral type.

Return Value
destination is returned.

memset

void * memset ( void * ptr, int value, size_t num );

Fill block of memory

Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).

Parameters

ptr
Pointer to the block of memory to fill.
value
Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num
Number of bytes to be set to the value.
size_t is an unsigned integral type.

Return Value
ptr is returned.

memcmp

int memcmp ( const void * ptr1, const void * ptr2, size_t num );

Compare two blocks of memory

Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.

Notice that, unlike strcmp, the function does not stop comparing after finding a null character.

Parameters
ptr1
Pointer to block of memory.
ptr2
Pointer to block of memory.
num
Number of bytes to compare.

Return Value
Returns an integral value indicating the relationship between the content of the memory blocks:

return valueindicates
<0the first byte that does not match in both memory blocks has a lower value in ptr1 than in ptr2 (if evaluated as unsigned char values)
0the contents of both memory blocks are equal
>0the first byte that does not match in both memory blocks has a greater value in ptr1 than in ptr2 (if evaluated as unsigned char values)

strcpy

char * strcpy ( char * destination, const char * source );

Copy string
Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
Parameters

destination
Pointer to the destination array where the content is to be copied.
source
C string to be copied.
Return Value
destination is returned.

strncpy

char * strncpy ( char * destination, const char * source, size_t num );

Copy characters from string
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

destination and source shall not overlap (see memmove for a safer alternative when overlapping).

Parameters
destination
Pointer to the destination array where the content is to be copied.
source
C string to be copied.
num
Maximum number of characters to be copied from source.
size_t is an unsigned integral type.

Return Value
destination is returned.

strcat

char * strcat ( char * destination, const char * source );

Concatenate strings
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

destination and source shall not overlap.
Parameters
destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.
source
C string to be appended. This should not overlap destination.

Return Value
destination is returned.

strncat

char * strncat ( char * destination, const char * source, size_t num );

Append characters from string
Appends the first num characters of source to destination, plus a terminating null-character.

If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.

Parameters

destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string, including the additional null-character.
source
C string to be appended.
num
Maximum number of characters to be appended.
size_t is an unsigned integral type.

Return Value
destination is returned.

strcmp

int strcmp ( const char * str1, const char * str2 );

Compare two strings
Compares the C string str1 to the C string str2.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.
Parameters
str1
C string to be compared.
str2
C string to be compared.

Return Value

Returns an integral value indicating the relationship between the strings:

return valueindicates
<0the first character that does not match has a lower value in ptr1 than in ptr2
0the contents of both strings are equal
>0the first character that does not match has a greater value in ptr1 than in ptr2

strncmp

int strncmp ( const char * str1, const char * str2, size_t num );

Compare characters of two strings
Compares up to num characters of the C string str1 to those of the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ, until a terminating null-character is reached, or until num characters match in both strings, whichever happens first.
Parameters
str1
C string to be compared.
str2
C string to be compared.
num
Maximum number of characters to compare.
size_t is an unsigned integral type.

Return Value
Returns an integral value indicating the relationship between the strings:

return valueindicates
<0the first character that does not match has a lower value in str1 than in str2
0the contents of both strings are equal
>0the first character that does not match has a greater value in str1 than in str2

strchr

const char * strchr ( const char * str, int character );      char * strchr (       char * str, int character );

Locate first occurrence of character in string
Returns a pointer to the first occurrence of character in the C string str.

The terminating null-character is considered part of the C string. Therefore, it can also be located in order to retrieve a pointer to the end of a string.
Parameters
str
C string.
character
Character to be located. It is passed as its int promotion, but it is internally converted back to char for the comparison.
Return Value
A pointer to the first occurrence of character in str.
If the character is not found, the function returns a null pointer.
Portability

In C, this function is only declared as:

char * strchr ( const char *, int );

instead of the two overloaded versions provided in C++.

strrchr

const char * strrchr ( const char * str, int character );      char * strrchr (       char * str, int character );

Locate last occurrence of character in string
Returns a pointer to the last occurrence of character in the C string str.

The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.

Parameters
str
C string.
character
Character to be located. It is passed as its int promotion, but it is internally converted back to char.
Return Value
A pointer to the last occurrence of character in str.
If the character is not found, the function returns a null pointer.
Portability
In C, this function is only declared as:

char * strrchr ( const char *, int );

instead of the two overloaded versions provided in C++.

strtok

char * strtok ( char * str, const char * delimiters );

Split string into tokens
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of the last token as the new starting location for scanning.

To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in delimiters (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in delimiters, which becomes the end of the token. The scan also stops if the terminating null character is found.

This end of the token is automatically replaced by a null-character, and the beginning of the token is returned by the function.

Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.

The point where the last token was found is kept internally by the function to be used on the next call (particular library implementations are not required to avoid data races).

Parameters

str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiter characters.
These can be different from one call to another.
Return Value

If a token is found, a pointer to the beginning of the token.
Otherwise, a null pointer.
A null pointer is always returned when the end of the string (i.e., a null character) is reached in the string being scanned.

strpbrk

const char * strpbrk ( const char * str1, const char * str2 );      char * strpbrk (       char * str1, const char * str2 );

Locate characters in string
Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.

The search does not include the terminating null-characters of either strings, but ends there.
Parameters
str1
C string to be scanned.
str2
C string containing the characters to match.
Return Value
A pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if none of the characters of str2 is found in str1 before the terminating null-character.
If none of the characters of str2 is present in str1, a null pointer is returned.

Portability
In C, this function is only declared as:

char * strpbrk ( const char *, const char * );

instead of the two overloaded versions provided in C++.

strstr

const char * strstr ( const char * str1, const char * str2 );      char * strstr (       char * str1, const char * str2 );

Locate substring
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

The matching process does not include the terminating null-characters, but it stops there.
Parameters
str1
C string to be scanned.
str2
C string containing the sequence of characters to match.

Return Value
A pointer to the first occurrence in str1 of the entire sequence of characters specified in str2, or a null pointer if the sequence is not present in str1.

Portability
In C, this function is only declared as:

char * strstr ( const char *, const char * );

instead of the two overloaded versions provided in C++.

strlen

size_t strlen ( const char * str );

Get string length
Returns the length of the C string str.

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

This should not be confused with the size of the array that holds the string. For example:

char mystr[100]="test string";

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

In C++, char_traits::length implements the same behavior.
Parameters
str
C string.

Return Value
The length of string.

stdlib.h

C Standard General Utilities Library
This header defines several general purpose functions, including dynamic memory management, random number generation, communication with the environment, integer arithmetics, searching, sorting and converting.

calloc

void* calloc (size_t num, size_t size);

Allocate and zero-initialize array
Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.

The effective result is the allocation of a zero-initialized memory block of (num*size) bytes.

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
Parameters
num
Number of elements to allocate.
size
Size of each element.

size_t is an unsigned integral type.

Return Value
On success, a pointer to the memory block allocated by the function.
The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.

Data races
Only the storage referenced by the returned pointer is modified. No other storage locations are accessed by the call.
If the function reuses the same unit of storage released by a deallocation function (such as free or realloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.

Exceptions (C++)
No-throw guarantee: this function never throws exceptions.

free

void free (void* ptr);

Deallocate memory block
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.

If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.

If ptr is a null pointer, the function does nothing.

Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location.

Parameters
ptr
Pointer to a memory block previously allocated with malloc, calloc or realloc.
Return Value
none

Data races
Only the storage referenced by ptr is modified. No other storage locations are accessed by the call.
If the function releases a unit of storage that is reused by a call to allocation functions (such as calloc or malloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.

Exceptions (C++)
No-throw guarantee: this function never throws exceptions.

If ptr does not point to a memory block previously allocated with malloc, calloc or realloc, and is not a null pointer, it causes undefined behavior.

malloc

void* malloc (size_t size);

Allocate memory block
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
Parameters
size
Size of the memory block, in bytes.
size_t is an unsigned integral type.

Return Value
On success, a pointer to the memory block allocated by the function.
The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.

Data races
Only the storage referenced by the returned pointer is modified. No other storage locations are accessed by the call.
If the function reuses the same unit of storage released by a deallocation function (such as free or realloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.

Exceptions (C++)
No-throw guarantee: this function never throws exceptions.

realloc

void* realloc (void* ptr, size_t size);

Reallocate memory block
Changes the size of the memory block pointed to by ptr.

The function may move the memory block to a new location (whose address is returned by the function).

The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved to a new location. If the new size is larger, the value of the newly allocated portion is indeterminate.

In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning.
C90 (C++98)
Otherwise, if size is zero, the memory previously allocated at ptr is deallocated as if a call to free was made, and a null pointer is returned.
C99/C11 (C++11)
If size is zero, the return value depends on the particular library implementation: it may either be a null pointer or some other location that shall not be dereferenced.

If the function fails to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged).
Parameters
ptr
Pointer to a memory block previously allocated with malloc, calloc or realloc.
Alternatively, this can be a null pointer, in which case a new block is allocated (as if malloc was called).
size
New size for the memory block, in bytes.
size_t is an unsigned integral type.

Return Value
A pointer to the reallocated memory block, which may be either the same as ptr or a new location.
The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
C90 (C++98)
A null-pointer indicates either that size was zero (an thus ptr was deallocated), or that the function did not allocate storage (and thus the block pointed by ptr was not modified).
C99/C11 (C++11)
A null-pointer indicates that the function failed to allocate storage, and thus the block pointed by ptr was not modified.

Data races
Only the storage referenced by ptr and by the returned pointer are modified. No other storage locations are accessed by the call.
If the function releases or reuses a unit of storage that is reused or released by another allocation or deallocation function, the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.

Exceptions (C++)
No-throw guarantee: this function never throws exceptions.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百口可乐__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值