string's null character

do i need to add
*t='\0';
after line 10....or is it copied from str1 itself??

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
int main()
{
    char str1[]="hello";
    char str2[10];
    char *t,*s;
    s=str1;
    t=str2;
    while(*t=*s)
    *t++=*s++;
    printf("%s\n",str2);
    getchar();
}
No, you shouldn't have to. But your code probably won't run as expected.

I have reformatted your code so it makes a little more sense:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>

int main()
{
    char *pStr1 = "hello";
    char vStr2[10];
    char *pS = pStr1;
    char *pT, = vStr2;

   while(*t != NULL || *s != NULL)
   {
        ++pT;
        ++pS;
        *pT = *pS;
   }

   printf("%s\n", vStr2);
   getc();

   return 0;
}


Now I'm going to explain my changes and why I made them.
Line 5: I changed your array of undefined size to a pointer. No need to worry, they are essentially the same and so many operations still work on a pointer that do an array.

Line 10: Saying while(*t=*s) will always be true and will always set *t to *s. I also did bound checking (crude and rusty) in this line making it so you didn't corrupt memory.

IN THE LOOP: I have made it so each loop iteration will increment your pointers, moving them along the array in memory, and setting the destination to the source *pT = *pS;

NOTE: This code may seem confusing at first, but that is because I am using a coding convention that makes sense to me. What is important here are the principles at work.
Last edited on
dont you think you arent copying the 1st letter of pSTR1???
Canonical:

1
2
3
4
5
6
7
const char str1[] = "hello" ;
char str2[ sizeof(str1) ] ;

// copy characters in str1 (including the null character) to str2 
char* dest = str2 ;
const char* srce = str1 ; // EDIT: made const-correct
while( ( *dest++ = *srce++ ) ) ;

Last edited on
> I changed your array of undefined size to a pointer.
It was not undefined, it was `as big to hold the string and terminator character'.
And string literals are const char*

> Saying while(*t=*s) will always be true
No, it fails when the assignment is zero.

> I also did bound checking
*t is not initialized at the start of the program.
can any 1 plz tell me when will while(*t=*s) return 0 in the above code??
I think you meant while ( *t++ = *s++ ) as JLBorges showed.

At first *t is assigned the value of *s and this value before incrementing pointer t becomes the result of the assignment operator which is tested in the while statement So if *s is equal to '\0' then at first it is assigned to *t and becomes the result of the assignment expression.
Topic archived. No new replies allowed.