Prachi Dutta
Prachi Dutta

Reputation: 11

Printing a string character-by-character

int main() {
    int i;
    char a[]={"Hello"};
    while(a!='\0') {
        printf("%c",*a);
        a++;
    }
    getch();
    return 0;
}

Strings are stored in contiguous memory locations & while passing the address to printf() it should print the character. I have jst started learning C. I am not able to find an answer to this. Pls help.

Upvotes: 1

Views: 285

Answers (4)

Mestica
Mestica

Reputation: 1529

You can also try it using a for loop:

#include <stdio.h>

int main(void) {
   char a[] = "Hello";
   char *p;

   for(p = a; *p != '\0'; p++) {
      printf("%c", *p);
   }

   return 0;
}

Upvotes: 0

Elazar
Elazar

Reputation: 21645

Three problems:

  1. char a[]={"Hello"}; is illegal. {"Hello"} can only initialize char* a[]. You probably want char a[]="Hello";
  2. while(a!='\0') - you probably meant *a != '\0'. a is the array itself.
  3. a++; - an array cannot be incremented. you should increment a pointer pointing to it.

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122493

In your code, a is a name of an array, you can't modify it like a++. Use a pointer like this:

char *p = "Hello";
while(*p++)
{
     printf("%c",*p);
}

Upvotes: 2

GeekFactory
GeekFactory

Reputation: 399

Well a is the name of the array which you cannot increment. It is illegal to change the address of the array.

So define a pointer to a and then increment

#include <stdio.h>
#include <conio.h>

 int main()
 {
     int i;
     char a[]="Hello";
     char *ptr = a;
     while(*ptr!='\0')
     {
         printf("%c",*ptr);
         // a++ here would be illegal
         ptr++;
     }
     getch();
     return 0;
 }

NOTE:

In fact, arrays in C are non-modifiable lvalues. There are no operations in C that can modify the array itself (only individual elements can be modifiable).

Upvotes: 5

Related Questions