Why this code does not work? :-(

Hi Guys,

A friend of mine asked me about this and I am totally stumped by this simple code. Could some one please tell me why this is not working?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

  1 #include <stdio.h>
  2 #include <string.h>
  3 #include<iostream>
  4 
  5 using namespace std;
  6 
  7 char *strcatt(char *s,char *t)
  8 {
  9 
 10 char *t1 = s ;
 11 
 12 while((*t1)!='\0') {
 13         t1++ ;
 14 }
 15 
 16 int i = 0;
 17 int j = strlen(s);
 18 while (i<strlen(t)) {
 19 
 20    t1[j] = t[i] ;
 21    i++; j++;
 22 }
 23 
 24 printf("%s\n",s); // just prints hello 
 30 return NULL;
 31 }
 32 
 33 
 34 main()
 35 {
 36 char fst[20] ;
 37 
 38 memset(fst,NULL,sizeof(fst)) ;
 39 strcpy(fst,"hello hiie");
 40

 45 char scnd[5] ;
 46 
 47 memset(scnd,NULL,sizeof(scnd)) ;
 48 strcpy(scnd,"baby");
 49 
 52  strcatt(fst,scnd);
 53 
 56 return 0;
 57 }


Last edited on
Figured it out. I think it's because of the fact that t1[5] is converted to t1 + 5 and since t1 is currently at hello'\0' (NULL) so when I try to put value at t1[5] it will actually be t1 + 5 which happens to be 5 elements from it's current position which happens to be NULL. Is it correct?
Last edited on
This part of the code is culprit, i don't know how these lines are useful to you:

1
2
3
while((*t1)!='\0') {
          t1++ ;
  }


just comment and you will get your desired results:
1
2
3
/*while((*t1)!='\0') {
          t1++ ;
  }*/

do you want to traverse till the end of the string stored in char *s and do something ?
strcat is what my friend was trying to do. I think the reason, as I mentioned above, is that array always indexes with respect to the starting address whereas pointer indexes with respect to the current address. That's why NULL in string 1 was there and was not working as expected.
Topic archived. No new replies allowed.