Reputation:
I read many previous questions but none of them cleared my doubt.
When I define and initialize a pointer as
int a = 10;
int* p;
p = &a;
printf("%d", *p); // this will print the value of 'a' towards which p is pointing
But when I use scanf statement like-
int *p;
scanf("%d", &p);
printf("%d", p); // is this form of input similar to the one above?
Also when I use char pointer to read a string-
char* name[10];
scanf("%s", name);
printf("%s", name); // runs correctly.
What I know is that scanf expects pointer as input (like &a
if it's like int a;
)
But If I use--
char* names[5][10];
scanf("%s", names[1]); // reading the first name. Is this correct? because length of name can vary.
Now I am unable to print this, I tried no of ways.
A detailed explanation would be appreciated, my teacher isn't that good.
DOUBTS
When do we use *
with a pointer? i.e. to print its value or for what?
Unable to scan char* xyz[a][b];
A brief explanation of my mistakes and the code above.
Edits-
int* arr[n];
for(int i =0; i<n; i++){
printf("Enter the salary of %d person:", i+1);
scanf("%d", &(arr[i]));
printf("\n");
}
Also, this type of assignment of value is not right?
Upvotes: 0
Views: 1081
Reputation: 134286
printf("%d", p); // is this form of input similar to the one above?
no, %d
expects an int
argument, you're passing an int *
. Supplying mismatched argument type for a conversion specifier invokes undefined behaviour.
That said, in case of
char* name[10]; // array of character pointers!
scanf("%s", name);
printf("%s", name); // runs correctly.
you're going wrong. Check the data types. %s
expects the argument to be a pointer to a char
array, so your code should be
char name[10]; // array of characters
scanf("%9s", name); // mandatory error check for success to be done.
printf("%s", name);
as, in most of the cases including this one, an array type decays to the pointer to the first element of the array, so while passing as function argument, name
is actually of type char *
.
Same goes with
char* names[5][10];
scanf("%s", names[1]);
changing that to
char names[5][10];
will suffice.
Upvotes: 0