How pointer adds extra value in printf? - c

#include <stdio.h>
int main() {
int *const volatile p=5;
printf("%d",5/2 + p);
return 0;
}
Without pointer, output is 7 and if I add pointer then the output of the answer is 13. Kindly give the step by step explanation of this program.

The code is invalid. The type of 5/2 + p is int *, while %d requires an int.
Kindly give the step by step explanation of this program.
5/2 + p = // 5/2 is equal to 2
2 + p = // p has type int
2 * sizeof(int) + (char*)p = // p is 5
2 * sizeof(int) + 5 = // sizeof(int) if 4 on your platform
2 * 4 + 5 =
13

Related

How to generate a random mathematical operator

I have an assignment that requires me to make a quiz which generates random math questions. I'm fine with everything but i'm struggling to find a way to randomly choose between the mathematical operators "+" and "-".
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int choice = 0;
int lives = 0;
int question = 1;
int a;
int b;
int answer = 0;
int ans = 0;
int correct = 0;
printf("\n Welcome to Maths Tester Pro.");
printf("\n Please Select a difficulty:");
printf("\n 1) Easy");
printf("\n 2) Medium");
printf("\n 3) Hard \n");
scanf("%d%*c",&choice);
switch(choice)
{
case 1:
printf("You have selected Easy mode!");
lives = lives+3;
while ((lives !=0)&&(question !=6)){
if(question !=5){
//Ask Question
printf("\nQuestion %d of 5. You have %d lives remaining", question, lives);
srand(time(NULL));
a = (rand() % (10 - 1 + 1)) + 1; //make the sign random
b = (rand() % (10 - 1 + 1)) + 1;
printf("\n%d + %d = ",a ,b);
scanf("%d", &answer);
ans = a+b;
//If answer is correct
if((a+b) == answer){
printf("Correct!\n");
correct = correct + 1;
}
//If answer is incorrect
else{
printf("Incorrect! The correct answer was %d\n",ans);
lives=lives-1;
}
question = question + 1;
}
In my code I have it written as ans=a+b but I want it to be able to randomly pick either "+" or "-".
The easiest way to go would be to change the sign of b. To do so, simply multiply it by either 1 (keeps positive sign) or -1 (makes it a negative):
b = b * ((rand() - (RAND_MAX / 2)) > 0 ? 1 : -1);
Upon execution, you will randomly get a + b or a + (-b).
Example print of the resulting operator:
printf("%d%s%d = %d\n", a, (b > 0 ? "+" : ""), b, a + b);
Note: as pointed in earlier comments, you may also want to randomize the seed in order to prevent you application to keep providing the "same" random numbers with:
/* Randomize seed (needed once). */
srand(time(NULL));
/* Then make your calls to `rand()`. */
...
I offer this as an example of how to cleanly generate and print the sort of problems that you seem to want.
This produces 20 'sum' and/or 'difference' equations. You can simply suppress printing the total in order to pose the question to the user.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand( time( NULL ) );
for( int i = 0; i < 20; i++ ) {
int a = (rand() % 10) + 1; // 1 <= a <= 10
int b = (rand() % 20) - 9; // -9 <= b <= 10
printf( "%d %c %d = %d\n", a, "+-"[b<0], abs( b ), a+b );
}
return 0;
}
1 + 3 = 4
1 - 6 = -5
4 + 10 = 14
8 + 2 = 10
10 + 0 = 10
4 + 4 = 8
8 + 10 = 18
8 + 9 = 17
8 - 2 = 6
8 - 4 = 4
2 + 1 = 3
8 - 5 = 3
2 - 6 = -4
4 + 9 = 13
6 + 6 = 12
5 + 0 = 5
3 + 4 = 7
1 + 0 = 1
9 - 5 = 4
8 + 8 = 16
The keen eyed reader will notice that even "10 + 0" is a reasonable problem. Zero is the identity operator(?) for addition (like 1 being the identity operator(?) for multiplication.)
You're free to adjust the ranges of the terms to suit your questions.
You can use rand() function, which is defined in stdlib. And if you want your program to give you different random numbers every time you run it, you need to put srand(time(NULL)) at the beginning, but for the time function, you need to include time.h library

What does ((short *)((((char *)(&arr[1]))+8))[3]=100; do?

...
int arr[5];
arr[3]=128;
((short *)((((char *)(&arr[1]))+8))[3]=100;
...
Above is part of a pretentious code.
What does
((short *)((((char *)(&arr[1])) + 8))[3] = 100
the line do? The following is my thought assuming char is 1 byte and int is 4 byte.
arr will look like arr[0], arr[1], arr[2], arr[3], arr[4] in memory with each 4 bytes. &arr[1] points to arr[1]. (char *)(&arr[1]) is treating arr[1] value 4 bytes as char each of 1 byte.
What is the function part of (char *)(&arr[1]) and ((char *)(&arr[1])) + 8 individually?
((short *)((((char *)(&arr[1])) + 8))[3] = 100
&arr[1]: is the address of the second int in arr (1*sizeof(int) from start).
((char *)(&arr[1])) : converts int address to a char address
(((char *)(&arr[1])) + 8) : adds 8 bytes to the char address
((short *)((((char *)(&arr[1])) + 8)): converts the char address to a short address
((short *)((((char *)(&arr[1])) + 8))[3]: treats the short address as a beginning of an array of storts and goes to the third element in this array (3 * sizeof(short) bytes).
((short *)((((char *)(&arr[1])) + 8))[3] = 100; : assigns 100
*((short*)(((char*)arr) + 1*sizeof(int) + 8 + 3*sizeof(short))) = 100;
The size of an int varies depending on processors but is often 4 bytes.
The size of a short varies depending on processors but is often 2 bytes.
*((short*)(((char*)arr) + 18)) = 100;
Let's split it up (ignoring unneeded brackets):
int* p0 = &arr[1];
char* p1 = (char *)p0;
char* p2 = p1 + 8;
short* p3 = (short *)p2;
p3[3] = 100;
Your arr array has 5 times an 4-bytes integer = a block of 20 bytes.
p0 points to the address of the second integer, so byte at index 4.
p1 stores p0 as address to chars / bytes.
p2 increases the value of p1 by 8 (chars) = points to byte at index 12.
p3 changes p2 to pointer type of 2-bytes (short) integer.
Last line points to fourth short (integer) value which means an address increment by 3 * 2 bytes = now we're at byte index 18 of arr. There we assign value 100 as the last two bytes (index 18 & 19) of our available memory.
In short:
((short *)arr)[9] = 100;
Full example:
#include <stdio.h> // printf
int main(void) {
// Initialize zero-filled memory
int arr[5] = {0};
// Write value 100 to last 2 bytes
((short*)arr)[9] = 100;
// Print memory
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
printf("%d ", arr[i]); // 0 0 0 0 6553600
}
it can be translated to:
short *ptr = (short *)(arr + 1 + 8 / sizeof(*arr)); // or &arr[1 + 8 / sizeof(*arr)]
ptr[3] = 100;

Exam Q&A that I don't understand [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The following code prints out 5. Can someone explain it to me? I think I am mostly confused about the math; for example, using '0' instead of 0 and how I can do that math on paper...
#include <stdio.h>
int main (int argc , char * argv [])
{
char * c_pt ;
int n = 0;
if( argc == 2)
{
c_pt = argv [1];
while (* c_pt )
{
if (* c_pt < '0' || * c_pt > '1') break ;
n = n*2 + * c_pt - '0';
c_pt ++;
}
printf ("%d\n", n);
}
}
When you access the characters in a string containing digits you might get the character '0' or '1' for example. But the integer value of '0' is 48 and the integer value of '1' is 49 so if you want to turn them into the integers 0 and 1 for arithmetic you need to substract something. You could subtract 48 but then the next person that reads your code has no idea why you did that. So nornally you subtract the character represented by the value: '0' - '0' = 0 and '1' - '0' = 1
This particular program reads a string containing a binary number from the command line (so the string contains the characters '0' and '1') and converts that binary number to a decimal number by first converting the '0' and '1' at *c_pt to 0 and 1 and then adding it to the decimal number being built in n. It does that by starting with 0 and then on each iteration multiplying the number by two (which just shifts everything left one bit) and then adding the next digit. So if the string contained 10101 it would follow these steps:
number = 0
input = 10101
pointer = ^
number = number*2 + *pointer = 0*2 + ('1'-'0') = 0*2 + 1 = 1 (in binary: 1)
input = 10101
pointer = ^
number = number*2 + *pointer = 1*2 + ('0'-'0') = 1*2 + 0 = 2 (in binary: 10)
input = 10101
pointer = ^
number = number*2 + *pointer = 2*2 + ('1'-'0') = 2*2 + 1 = 5 (in binary: 101)
input = 10101
pointer = ^
number = number*2 + *pointer = 5*2 + ('0'-'0') = 5*2 + 0 = 10 (in binary: 1010)
input = 10101
pointer = ^
number = number*2 + *pointer = 10*2 + ('1'-'0') = 10*2 + 1 = 21 (in binary: 10101)
void main ( void )
{
int a[] = {22, 33,44};
'a' is a static array (or string) of 3 int, 22, 33, and 44.
int *x = a;
'x' is an int pointer, initialized to point to the same static array as 'a'.
printf (" sizeof ( int )=% lu ", sizeof (int ));
Prints the number of bytes [4] required to represent an int type on this system.
printf ("x=%p, x [0]=% d\n", x, x [0]);
Prints the memory address where the int pointer 'x' is currently pointing[0x7fff29af6530],
then also prints the integer value [22] stored in the [4] bytes starting at that address.
(Note: 'x[0]' is the same as '*x').
x = x + 2;
x [0x7fff29af6530]
+2 + 8 (or (2 * 4) or (2 * sizeof(int)))
---- ----------------
new x [0x7fff29af6538]
Advance the pointer 'x' 8 bytes.
The effect on 'x' is that it will now be pointing at its original memory address plus '(2 * sizeof(int))' bytes. 'a[2]' resolves to the same location.
printf ("x=%p, x [0]=% d\n", x, x[0]);
Prints the memory address where the int pointer 'x' is currently pointing [0x7fff29af6538]
then also prints the integer value [44] stored in the [4] bytes starting at that address.
Hence; 'x' now resolves to the same address as '&a[2]'; and '*x' resolves to the same number as 'a[2]'.
}

How to format output correctly for this program?

I created a program that manually converts a base 10 number to any other base. I have the important things working I think but there are a couple of problems that I can't fix.
One problem I have is that the formatting of the remainder in parenthesis on the far right of each line does not line up properly. I realize that this isn't really a necessary thing but my professor wants the output to be in such a way and will take off points if it isn't. FIXED
A bigger problem I am having is that the final line of output, the hexadecimal number, will be correct but there is sometimes a stray ASCII character or several spaces between 0x and the hex.
Here is an example of bad output UPDATE:
Marcus Lorenzana
8526495043095935640 = 532905940193495977 * 16 + 8 (8)
532905940193495977 = 33306621262093498 * 16 + 9 (9)
33306621262093498 = 2081663828880843 * 16 + 10 (A)
2081663828880843 = 130103989305052 * 16 + 11 (B)
130103989305052 = 8131499331565 * 16 + 12 (C)
8131499331565 = 508218708222 * 16 + 13 (D)
508218708222 = 31763669263 * 16 + 14 (E)
31763669263 = 1985229328 * 16 + 15 (F)
1985229328 = 124076833 * 16 + 0 (0)
124076833 = 7754802 * 16 + 1 (1)
7754802 = 484675 * 16 + 2 (2)
484675 = 30292 * 16 + 3 (3)
30292 = 1893 * 16 + 4 (4)
1893 = 118 * 16 + 5 (5)
118 = 7 * 16 + 6 (6)
7 = 0 * 16 + 7 (7)
����76543210FEDCBA98
It should look something like this:
Marcus Lorenzana
2147483647 = 134217727 * 16 + 15 (F)
134217727 = 8388607 * 16 + 15 (F)
8388607 = 524287 * 16 + 15 (F)
524287 = 32767 * 16 + 15 (F)
32767 = 2047 * 16 + 15 (F)
2047 = 127 * 16 + 15 (F)
127 = 7 * 16 + 15 (F)
7 = 0 * 16 + 7 (7)
0x7FFFFFFF
This is my program UPDATED:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER 50
static const char hexstr[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main(int argc, char * argv[]) {
if (argc == 3) {
int base = atoi(argv[1]);
int i = 0;
long oldresult;
int remainder;
char remainders[BUFFER];
char w_num[BUFFER];
long value = atol(argv[2]);
int width = sprintf(w_num,"%ld",value);
printf("Marcus Lorenzana\n");
while(value != 0) {
oldresult=value;
remainder = value%base;
value = value/base;
remainders[i]=hexstr[remainder];
char line[BUFFER];
int w = sprintf(line,"%*ld = %ld * %d + %d", \
width,oldresult,value,base,remainder);
printf("%s%*s(%c)\n",line,50-w,"",hexstr[remainder]);
i++;
}
int x = strlen(remainders);
while(x > 0) {
printf("%c",remainders[--x]);
}
printf("\n");
} else {
printf("Error: Wrong arguments\n");
}
return 0;
}
Use the return value from printf() to determine how many spaces to print before the remainder.
int w = printf("%*lld = %lld * %d + %d",width,oldresult,value,base,remainder);
if (remainder > 9) {
remainders[i]=hexstr[remainder-10];
// Here and in the else clause
printf("%*s(%c)\n", 34-w, "", hexstr[remainder-10]);
}
2nd issue: Change how x is tested and decremented. Do not see where "0x" occurs.
while(x > 0) {
printf("%c",remainders[--x]);
}
Note: seems like static const char hexstr[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; would simplify things.
[Edit]
Simple fix for 2nd issue as remainders is never properly \0 terminated.
// int x = strlen(remainders);
int x = i;

Pointer in C, don't understand how they got this result

here is code snippet
void F (int a, int *b)
{
a = 7 ;
*b = a ;
b = &a ;
*b = 4 ;
printf("%d, %d\n", a, *b) ;
}
int main()
{
int m = 3, n = 5;
F(m, &n) ;
printf("%d, %d\n", m, n) ;
return 0;
}
answer
4 4
3 7
I see how 4 4 was computed, I don't get how they got 3 7 (I do understand how 3 is computed, it is not changed since it was not passed by reference)
Thanks !
I've annotated the F function with comments to explain what's going on:
a = 7 ; // a is now 7
*b = a ; // b points to n, so n is now 7
b = &a ; // b now points to a and no longer to n
*b = 4 ; // a is now 4. n is unaffected
At the start of main, we have
m=3 n=5 // int m = 3, n = 5;
then we call F(m, &n), passing m by value, and n by pointer
such that
m = 3 n = 5
a = 3 b->n // F(m, &n);
Now, inside F(), we assign 7 to a:
m = 3 n = 5
a = 7 b->n // a = 7
then we assign a (=7) to the memory address pointed by b (->n)
m = 3 n = 7
a = 7 b->n // *b = a;
next we change b, so that now b points to a:
m = 3 n = 7
a = 7 b->a // b = &a;
and then we assign 4 to the memory address pointed by b (->a)
m = 3 n = 7
a = 4 b->a // *b = 4;
printing a (=4) and *b (->a =4)
and printing m (=3) and n (=7) outside the function
Take a close look at this line
b = &a ;
*b = 4 ;
b gets the reference of a (it's memory address). When you now access *b it points to the memory of the variable a, not to n anymore
Quite subtle indeed. :)
In F a lot of nonsense happens: whichever value is passed via a, it's discarded, and instead 7 is assigned to it. Then, the value of a (which is 7) is assigned to the variable to which b points (which is n, so it's here that n becomes 7).
At the next line, the object to which b points is changed, so that b now points to the local parameter a, and at the following line the object pointed by b (=>a) is set to 4.
Thus, now we have a that is 4, b that points to a (=>so *b==4, since *b==a), m is still 3 (it was passed by value, so it couldn't have been changed by F) and n was set to 7.
By the way, this is exactly the mess you shouldn't to at all in your applications to avoid confusing any people who have the disgrace to work on them. :)

Resources