1
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.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
  • 3
    The first problem is your title. It's not informative, please edit it. – Maroun Jul 01 '13 at 13:07
  • possible duplicate of [What is the difference between char s\[\] and char \*s in C?](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c) – CB Bailey Jul 01 '13 at 13:09
  • Not really an exact duplicate of the question but you are trying to use an array as if it were a pointer so I believe that the answer to the linked question should also answer your question. – CB Bailey Jul 01 '13 at 13:10
  • `man putc`, `man fputc` Using `printf` to print a single character is not wrong, but a bit strange. – William Pursell Jul 01 '13 at 13:29

4 Answers4

5

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).

GeekFactory
  • 399
  • 2
  • 13
2

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);
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

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.
Elazar
  • 20,415
  • 4
  • 46
  • 67
0

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;
}
Mestica
  • 1,489
  • 4
  • 23
  • 33