Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
hi
I have a quite strange problem in one of my programs. I'd like to strcat(string1,"test") two strings, but after that, string1 hasnt changed at all !?! How can this be?
Here is some more code:
void func(void)
{
char *string1;
string1 = "";
.
.
.
strcpy(string1,func2()) //this one works perfectly well (func2 is a function which returns a string)
strcat(string1, "D") //this one doesnt't work. The "D" isnt added to string1
.
.
.
}func is called many times by main. The problem occurs only after the fith or sixth call. The first few times, everything works fine. Could it be a problem with memory allocation or something like that? I really have no clue and I'd be grateful for every hint.
Hope I posted enough information; if not please tell me.thanks
rde

You are not allocating memory for the string in question. You can either
char string[10];
or
char *string1;
string1 = new char[10];say string1 already contains 9 characters (the trailing \0 is the tenth character) and you want to cat another string, you would have to:
char *string2;
string2 = new char[strlen(string)+strlen(func())];
strcpy(string2,string1);
strcat(string2,func());

Of course I made a mistake, the line should read:
string2 = new char[strlen(string1) + strlen(func() + 1)];

Of course I made another mistake, the line should read:
string2 = new char[strlen(string1) + strlen(func()) +1];
It's late, I'm tired, give me a break.

You know what, forget char strings. Just use strings, as in:
#include string
string s1 = "Whatever";
string s2 = "Other stuff";
string s3 = string1 + string2;
// s3 is now "WhateverOther stuff"strings are so much easier to use than messing around with char arrays, except for tokenizing.

![]() |
Perl STDIN
|
programming help in c ple...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |