Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

scanf statement in c and pointers

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(" ");
    }

Also, this type of assignment of value is not right?

question from:https://stackoverflow.com/questions/65558276/scanf-statement-in-c-and-pointers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
   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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...