Reputation: 1
#include <stdio.h>
int main()
{
char s[] = "churchgate: no church no gate";
char t[25];
char *ss, *tt;
ss = s;
while (*ss != '\0')
*tt++ = *ss++;
printf("%s\n", t);
return 0;
}
what is the problem with this code? when I try to run it. Its showing up some garbage values.
Upvotes: 0
Views: 281
Reputation: 91029
Several possibilities, e. g.:
#include <stdio.h>
int main()
{
char s[] = "churchgate: no church no gate";
char t[25];
char *ss, *tt;
for (ss=s, tt=t; *ss != '\0' && tt-t < sizeof(t)-1; ss++, tt++)
*tt = *ss;
}
*tt = '\0';
// or just use strncpy.
// strncpy doesn't copy the \0 if the size is reached,
// so account for that.
strncpy(t, s, sizeof(t)-1);
t[sizeof(t)-1] = '\0';
printf("%s\n", t);
return 0;
}
You know your major problems from the other answers:
tt
uninitializedt
Upvotes: 0
Reputation: 93
Tho it can be fun to experiment with arbitrary locations in memory, if you want a defined behaviour the target of access has to be defined.
tt has to be pointed towards some defined area in memory space before you do operations on it.
*tt++ = *ss++;
s
is 30 bytes. t
, if that is the one you want to use for tt
is 25.
Upvotes: 1
Reputation: 121649
Several problems:
1) "tt" was never initialized, and
2) "s[]" might be READ ONLY (depending on compiler/platform)!!!!!
Suggestion:
#include <stdio.h>
#define MAX_STRING 80
int
main()
{
char s[MAX_STRING] = "churchgate: no church no gate";
char t[MAX_STRING];
char *ss = s, *tt = t;
while (*ss)
*tt++ = *ss++;
*tt = '\0';
printf("%s\n", t);
return 0;
}
Upvotes: 0
Reputation: 145829
tt
to t
Upvotes: 3
Reputation: 134157
You never point tt
to anything. You need to point it to t
:
tt=t;
Upvotes: 3