Home > front end >  Why unwanted character getting showed when I print a string
Why unwanted character getting showed when I print a string

Time:11-12

#include<stdio.h>
int main()
{
    char main[]="Structured Programming";
    char copy[30];
    for (int i = 0; main[i] !='\0' ; i  )
    {
        copy[i]=main[i];
    }
    printf("%s",copy);
}

In the above problem this just should print Structured Programming, but I'm getting Structured Programming a, this happens on all ide's, but not on online compilers, online compilers are working fine, can anyone tell me the reason?

CodePudding user response:

printf function expects NULL terminated string to print. Otherwise your program could access extra bytes of string that you don't want to. It depends on environment and compiler how to react to this situation but generally it's undefined behavior. You should make last symbol of your string equal to '\0' to fix it.

CodePudding user response:

Sometimes "undefined behavior" means it appears to work. You can initialize copy, or simply copy the NUL:

i = 0;
do  {
    copy[i] = main[i];
    } while (main[i  ]);

CodePudding user response:

This for loop

for (int i = 0; main[i] !='\0' ; i  )
{
    copy[i]=main[i];
}

does not copy the terminating zero character '\0' of the source string stored in the array main in the array copy.

So the array copy does not contain a string. But the conversion specification %s expects a corresponding argument that is a pointer that points to a string. Thus this call of printf

printf("%s",copy);

invokes undefined behavior.

There are several ways to resolve the problem.

For example you could initially zero-initialize the array copy like

`char copy[30] = ""`;

Another way is to copy the terminating zero character '\0' in the destination array as for example

for ( int i = 0; ( cooy[i] = main[i] ) !='\0' ; i  );

Or you could output the array specifying the precision field in the call of printf as for example

int i = 0;
for ( ; main[i] !='\0' ; i   )
{
    copy[i] = main[i];
}
printf( "%.*s\n", i, copy );

Pay attention to that instead of the manually written for loop you could use standard function strcpy declared in the header <string.h> like

#include <string.h>

//...

puts( strcpy( copy, main ) );
  • Related