更新时间:2023-02-23 09:56:21
在文章< 3f *********************** @ news.xs4all.nl>中,Rick写道:
In article <3f***********************@news.xs4all.nl>, Rick wrote:
Hi,
This is probably simple byt when you never did pointers and being used to
luxery strings like in Delphi or Visual Basic, C can get though. What I''m
trying to do is to add chars to a string.
您是否调查了strcat()和strncat()?
-
Andreas K?h?ri
Did you investigate strcat() and strncat()?
--
Andreas K?h?ri
要添加,我认为result2会被result1以某种方式覆盖。当那些2
被初始化时,它们会自动获得一个内存地址,而且当我将结果添加到result1时,似乎
,结果2不会进一步移动。结果1
可能只获得1个字节的内存,因此在添加第二个字符时,它的数量为b
。结果2上的和contineus。
如果这是真的,那将是非常危险的,因为我可以覆盖程序中的大部分内容。通常你可以使用数组和malloc它们,但在我的情况下,我真的不知道结果有多大。在构建
结果字符串时,我需要至少1个子字符串用于其他东西,该字符串有
同样的问题,我无法计算它有多大,它必须动态增长
。怎么处理这个?
问候,
Rick
To add, I think result2 get''s overwritten by result1 somehow. When those 2
got initialized they get a memory adress automatically and it seems that
when I''m adding chars to result1, result2 won''t move further. Result1
probably only get 1 byte of memory so when adding the second char it''s "out
of bounds" and contineus on result2.
If this is true, that would be quiete dangerous because I could overwrite a
big part of the program. Normally you can use arrays and malloc them but in
my case, I really don''t know how big the result becomes. While building the
result string, I need at least 1 sub string for other stuff, that string has
the same problem, I can''t calculate how big it becomes, it has to grow
dynamically. How to handle this?
Greetings,
Rick
你的答案比光快!我只是试了但是同样的问题
(看到其他帖子,我解释了问题一点点)。或者
也许我使用的代码错了,这就是我用strncat做的:
char * res1 ="" ;;
char * res2 ="" ;;
strncat(res1," a",1);
strncat(res1," b", 1);
strncat(res1," c",1);
strncat(res2," 1",1);
strncat(res2," 2",1);
strncat(res2," 3",1);
printf(" result1%s \ n",res1);
printf(" result2%s \ n",res2);
结果:res1 =" abc" RES2 = QUOT; bc123" ;.当使用strcat时一样。
问候,
Rick
You answered faster than the light! I just tried it but the same problem
(see that other post where I explained the problem a little bit more). Or
maybe I am using the code wrong, this is what I did with strncat:
char *res1 = "";
char *res2 = "";
strncat( res1, "a",1 );
strncat( res1, "b",1 );
strncat( res1, "c",1 );
strncat( res2, "1",1 );
strncat( res2, "2",1 );
strncat( res2, "3",1 );
printf( "result1 %s\n",res1 );
printf( "result2 %s\n",res2 );
result : res1 = "abc" res2="bc123". When using strcat the same.
Greetings,
Rick