please help me to find the error in this C code [closed]

Your code has several issues, not only one:

1.

You use the wrong format specifier %c to catch a single character instead of %s to catch a string:

char arr[23];
printf("Enter your name: \n");`
scanf("%c",&arr[i]);

Rather use scanf("%s",arr); or even better scanf("%Ns",arr); where N stands for the maximum number of characters to be entered. Note that you need one element for the string-terminating null character, so it requires to be at least one character less than the char array is consisted of.

You can also use fgets(arr,23,stdin) which is preferred for consuming strings from the standard input because it is more safe as it requires you to provide the maximum amount of characters to read (counting the null character too) and also reads white space separated words as part of the string by default.


2.

i is not initialized to any value, so:

scanf("%c",&arr[i]);

causes undefined behavior.


3.

Furthermore you try to get a string length by using strlen() as part of the condition expression of the for loop:

for(int v = 0; v <= strlen(arr); v++)

although there is no valid string in arr which causes also undefined behavior.

As a side note here: It is more efficient to use strlen() only once before the for loop, store its return value in an object of an appropriate type (size_t is the type of the return value of strlen()) and use that object in the condition of the for loop instead of executing strlen() before each iteration.


4.

Next thing is that you attempt to print characters inside the for loop which arenĀ“t provided/initialized to arr:

for(int v = 0; v <= strlen(arr); v++)
{
   printf("%c",arr[v]);
}

5.

The for loop with the condition v <= strlen():

for(int v = 0; v <= strlen(arr); v++)

runs one time more than expected and prints the null character which is redundant since the null character is not printable.

Rather use v < strlen() or according to point 3:

    size_t len = strlen(arr);

    for(int v = 0; v < len; v++)

6.

The return value of main shall be int, not void.


7.

There is a trailing apostrophe after the printf() call:

printf("Enter your name: \n");`

Rather use:

#include <stdio.h>

int main()
{
    char arr[23];

    printf("Enter your name: \n");

    scanf("%22s",arr);

    printf("%s",arr);
}

Online Example

if you want to print out the string entered as whole at once, or:

#include <stdio.h>
#include <string.h>

int main()
{
    char arr[23];

    printf("Enter your name: \n");

    scanf("%22s",arr);

    size_t len = strlen(arr);

    for(int v = 0; v < len; v++)
    {
        printf("%c",arr[v]);
    }        
}

Online example

if you want to print each character separate.

Leave a Comment