-22
#include<stdio.h>    
int main()
{
  char *p = NULL;
  char str[] = "How do you do!!!!!";
  p = &str;
  printf("String is:%s",p);
  p = "HELLO HOW ARE YOU";

  printf("String is:%s",p);
  printf("Hello");


  int a = 10;
  int *pa;
  pa = &a;
  printf("Contents of a is %d\n",a);
  printf("Contents of pa is %x\n", (int)pa);
  printf("Values of variable pointed to by pa is %d\n", *pa);

  return 0;
}

While referring to the above code :

p = &str;
printf("String is:%s",p);

p will display string stored.

pa = &a;
printf("Values of variable pointed to by pa is %d\n", *pa);

But here if i want to display value of a=10 I will have to write *pa.

Why so ? What's the difference between the two ?

Why one show right when used p and other will show right when used *pa

In one case derefernce operator is used and in other it is not required

Drax
  • 12,682
  • 7
  • 45
  • 85
  • 4
    First of all, fix your horrible formatting. – Baum mit Augen Jul 24 '15 at 10:47
  • The following issues need to be resolved: the title should reflect the problem you're having, and would be very similar to what you type into google if you were searching for an answer to your problem. Secondly I bet there are a few dupes of this around, but don't know the terms well enough to find them. – George Stocker Jul 24 '15 at 11:50
  • This might help understand: http://stackoverflow.com/q/2528318/1147772 – Drax Jul 24 '15 at 16:00

2 Answers2

5

Read the basics of printf() and the format specifiers.

  • %s expects a "pointer" type (to be exact, "pointer to the initial element of an array of character type")argument, so, we're passing pointer.
  • %d expects an int as argument, so, we need to pass the variable value, i.e., de-reference the pointer.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
-3

First of all the compiler should issue a diagnostic message at least for statement

p = &str;

because there is no implicit conversion between types char * (the type of p) and char ( * )[19] that is the type of expression &str

So you have to write simply

p = str;

The reason for that the printf prints the same string is because the value of expressions &str and str is the same.

To print a string you have to specify format specifier %s and corresponding argument shall be a pointer to char.

printf("String is:%s",p);

When you want to print a scalar value like an object of type int you have to specify it itself as an argument of printf In this statement

printf("Values of variable pointed to by pa is %d\n", *pa);

expression *pa is indeed an object of type int.

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