scanf(...)

Hello all,

I have a problem interpreting the code. I know that scanf will pass stdin into the second argument, but in my case the second argument is the addition of two integers. What does this do?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int *buffer;
int nextp=0,nextc=0;
int mutex,full,empty;    /* semaphore variables
						  * mutex - binary semaphore -- critical section
 						  *	full, empty - counting semaphore */

void producer()	{
 	int data;
 	if(nextp == N) //N has been defined as 3, but why? Probably, because they only want three iterations or processes to run.
 		nextp=0;
 	printf("\nEnter the data(producer) :");
 		//You're using scanf() to get userinput in C, like you're using std::cin in C++. 
 		//"%d" for int ,"%f" for float ,"%e" for a scientific notation (1e10) ,"%c" for char , "%s" for strings.
 	scanf("%d",(buffer+nextp));			//second arg might need & to vars.
 	nextp++;
 }
the second argument is the addition of two integers.

No. It's the addition of an integer to a pointer.

It has the same effect as an array subscript.

*(buffer+nextp)
is the same as
buffer[nextp]

buffer[nextp]

So, this would do:
buffer[nextp]=whatever is passed as user input?
Thank you, Chervil!
There is a little detail here, scanf expects pointers to the memory.

To read one integer, one would do this:
1
2
int i;
scanf("%d", &i);


If you have an array, then using the subscript operator is as such:
1
2
3
int arr[10];
scanf("%d", &arr[0]);
scanf("%d", &arr[1]);


Using the "*" will deference a pointer, but since your array is already a pointer, you only need the parenthesis:
1
2
3
int arr[10];
scanf("%d", arr);
scanf("%d", ( arr + 1 ));
Last edited on
Are you saying that the code is wrong and it doesn't work as it should?
The original code looks like this:
scanf("%d",(buffer+nextp));

... and is correct according to the description given by LowestOne.
There's nothing wrong with the code you posted.

This:
1
2
if(nextp == N)
  nextp=0;


I can only assume is representing a circular buffer.
Yes, that's what I assumed too.

I assume you were elaborating on the answer, LowestOne?
g=*(buffer+nextc++);

Does this mean:
1
2
g=buffer[nextc];
nextc++;
?
Last edited on
Topic archived. No new replies allowed.