Kunal Bisht
Kunal Bisht

Reputation: 1

string code showing error?

#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

Answers (5)

glglgl
glglgl

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:

  1. tt uninitialized
  2. no bounds checking for t
  3. no 0-termination after copying

Upvotes: 0

Luca Stein
Luca Stein

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

paulsm4
paulsm4

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

ouah
ouah

Reputation: 145829

  1. You forgot to inialize tt to t
  2. Your array is too small.
  3. You forgot to null terminate your array.

Upvotes: 3

Justin Ethier
Justin Ethier

Reputation: 134157

You never point tt to anything. You need to point it to t:

tt=t; 

Upvotes: 3

Related Questions