1

This code is for declaring and printing a string using pointer concept

char *strPtr = "HelloWorld";

// temporary pointer to iterate over the string
char *temp = strPtr;
while (*temp != '\0') 
{
    printf("%c", *temp);
    temp++;
}

In this code I just want to replace the while loop to for loop. But when trying the code does not give any output. My code is as follows

char *name = "SAMPLE NAME";
int i;
for (i = 0; name[i] != '\0'; i++)
{
    printf("%c", *name);
}

This code Does Not work. [Gives blank output] Where is the error ??

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

0

This for loop

for (i = 0; name[i] != '\0'; i++)
{
    printf("%c", *name);
}

should output the first character of the string pointed to by the pointer name as many times as the length of the string due to this statement

    printf("%c", *name);

where there is used the same expression *name in the call of printf that is equivalent to expression name[0].

Also after the loop you should output the new line character '\n'.

So the loop should look like

for (i = 0; name[i] != '\0'; i++)
{
    printf("%c", name[i]);
}
putchar( '\n' );

If you want to use a pointer to output the string using for loop then it can look the following way

for ( const char *p = name; *p != '\0'; p++)
{
    printf("%c", *p);
}
putchar( '\n' );

Pay attention to that though in C string literals have types of non-constant character arrays nevertheless you may not change a string literal. Any attempt to change a string literal results in undefined behavior. Thus it is better to declare the pointer name with qualifier const

const char *name = "SAMPLE NAME";
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • why would it repeat due to `*name` –  Apr 07 '23 at 13:57
  • @Theprofessor See my updated answer. The pointer name is not being changed within the for loop. So it still points to the first character of the string literal. – Vlad from Moscow Apr 07 '23 at 13:58
  • also in using pointer i.e second attempt is it compulsory to declare a new `const char *p`variable.Can't i iterate using same variable `name` –  Apr 07 '23 at 14:12
  • @Theprofessor In that case you will lose the pointer to the string literal. So if you will need it one more you can not determine the address of the string literal. – Vlad from Moscow Apr 07 '23 at 16:10