Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
I cant get strcat to work. I tried ...
I can't get strcat to work. I tried
char *s1 = "Hello, ";br>
char *s2 = "world!";br>
char *s3 = strcat(s1, s2);br>
but I got strange results.
✍: Guest
the main problem here is that space for the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers allocate memory only for objects explicitly mentioned in the source code (in the case of strings, this includes character arrays and string literals). The programmer must arrange for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by calling malloc.
strcat performs no allocation; the second string is appended to the first one, in place. The first (destination) string must be writable and have enough room for the concatenated result. Therefore, one fix would be to declare the first string as an array:
char s1[20] = "Hello, ";
(In production code, of course, we wouldn't use magic numbers like ``20''; we'd use more robust mechanisms to guarantee sufficient space.)
Since strcat returns the value of its first argument (s1, in this case), the variable s3 in the question above is superfluous; after the call to strcat, s1 contains the result.
The original call to strcat in the question actually has two problems: the string literal pointed to by s1, besides not being big enough for any concatenated text, is not necessarily writable at all.
2016-03-09, 991👍, 0💬
Popular Posts:
How To Change System Global Area (SGA)? - Oracle DBA FAQ - Introduction to Oracle Database 10g Expre...
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 1...
What is a fish bone diagram ? Dr. Kaoru Ishikawa, invented the fishbone diagram. Therefore, it can b...
What is the difference between include directive & jsp:include action? Difference between includ...
How To Compare Two Strings with strcmp()? - PHP Script Tips - PHP Built-in Functions for Strings PHP...