问题描述
我刚接触C.我读对C一个查找替换算法和我有点困惑是什么 -
&安培; +
运营商在这种code做的:
的char *取代(的char * SRC,为const char *搜索,为const char *代替){
字符*缓冲=的malloc(4096); //在内存中新字符串分配4096个字节
字符* P; //我在src字符串搜索的字符串
INT I; P =的strstr(SRC,搜索);
如果(NULL == p)的回报SRC;如果//'搜索'对'src'中的回报SRC未找到
我= P - SRC; //我的子指数 函数strncpy(缓冲液,SRC,ⅰ); //复制子值缓冲
sprintf的(缓冲+ I,%s%S,更换,
P + strlen的(搜索)); //? 返回缓冲区;
}
由于 P
是在你的字符数组(字符串)和 SRC的位置
是它的开始,
I = P - SRC;
将设置 I
来的索引, P
分。
例如,请考虑以下的内存布局:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]&下; - 索引
123 124 125 126 127 128 129 130 131 132 LT; - 地址
+ --- + --- + --- + --- + --- + --- + --- + --- + --- + ---- +
| H |我| ,| | W | Ø| - [R |升|开发| \\ 0 |
+ --- + --- + --- + --- + --- + --- + --- + --- + --- + ---- +
^^
| |
SRC p
在这种情况下,对 - SRC
会给你 127 - 123
或 4
,这是中的是W
指数你好,世界
。
这就是所谓的指针运算在覆盖加法运算符
ISO标准( C99 6.5.6 / 9
):
It provides a scaled way of working out differences within the same array or with one pointing just beyond the end of the array (all else is undefined).
By that I mean doing pointer arithmetic with (for example) four-byte integers, will give you a difference of one between the addresses of arr[7]
and arr[8]
, not four as some may think.
The buffer + i
construct is simply another way of saying &(buffer[i])
, the address of the i
th element of the array buffer
. I actually prefer the latter method since it seems more explicit in what I'm trying to represent.
For what it's worth, that's not actually a very good string replacement code. It has numerous problems:
- if no replacements are made, you have a 4K memory leak with
buffer
. - in any case, you should always check to ensure
malloc
hasn't failed. - you have a possibility of buffer overflow the way the new string is allocated, you should really allocate based on the lengths of
src
search
andreplace
. - you could create the new string with a single
sprintf ("%*.*s%s%s", i, i, src, replace, &(src[i + strlen (search)]));
or astrcpy
and twostrcat
operations. Mixing the two seems incongruous to me.
这篇关于什么是 - 运营商做的char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!