C function calculates wrong with pointers [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
so i've been on trying to coding my first commandline game. I've been coding in C now for about a few months and it's my first coding language. I had no real problems until i came to the point where i had to deal with this pointer conversion.
Here is my function:
void attack(int * life, int * armor, char * name){
int difference;
const int damage = 15;
print_Name(name);
printf(" attacks!\n");
if((*armor) > damage){
printf("The armor was able to defend the damage!\n\n\n");
(*armor) = armor - damage;
}
if((*amor) <= damage){
printf("Your Armor broke!\n");
difference = damage - (*armor);
(*life) = (*life) - difference;
(*armor) = 0;
printf("The attack caused %i damage.\n\n\n", difference);
}
else if ((*armor) == 0){
printf("\nThe attack has caused %i damage.\n\n\n", damage);
(*life) = life - damage;
};
}
i translated my variables from german into english for a better understandment, but there might eventually be some typos.
the problem is, my game work fine for a few rounds. But after ~20-30 rounds i noticed that the damage output was wrong at some point and now i ran into this:
enter image description here
i know there is something wrong with my if's and that there is a better way to work around with the pointer... Can you help me with my problem?

If you read the warnings that your compiler emits, they'll tell you exactly what the problem is, as well as how to fix it:
q58348638.c:11:18: warning: incompatible pointer to integer conversion assigning
to 'int' from 'int *'; dereference with * [-Wint-conversion]
(*armor) = armor - damage;
^ ~~~~~~~~~~~~~~
*( )
q58348638.c:24:13: warning: incompatible pointer to integer conversion assigning
to 'int' from 'int *'; dereference with * [-Wint-conversion]
(*life) = life - damage;
^ ~~~~~~~~~~~~~
*( )
In case that still isn't clear enough, the problem is that you're setting the value of armor to the address of armor minus the value of damage. Instead, you need to set the value of armor to the value of armor minus the value of damage, so use * before armor, just like where you correctly did (*life) = (*life) - difference;.

Welcome to StackOverflow! Make sure you post code that compiles, runs, and exhibits the problem you are trying to solve.
This code has errors that may or may not be part of your original code. You've used damage instead of *damage once, used armor instead of *armor elsewhere and spelled it amor in another place.
One thing that can help cut down on error in your actual code is to use augmented assignment (+= -= *= etc.) especially when the object you are modifying is specified by an expression. For example:
*armor -= damage; // subtracts (damage) from (*armor)
Another is to turn on all warnings, pay attention to what they warn about. Don't consider your code ready for testing until all warnings are gone. For GNU gcc and compatible compilers like clang, I use both -Wall and add -Wextra and -pedantic to the command line (or project settings). Using Visual C++ as a C compiler, use /W4 instead of the default /W3. This will save you a lot of debugging time.
Note: You mentioned Visual Studio Code in a comment. I don't use that. It seems like a pain to set up compared to Visual Studio or Code::Blocks, but it seems you can specify command line options in your project's c_cpp_properties.json file. Try adding the line:
"compilerArgs": [
"/W4"
]

Related

Variable in C not printing the given value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Alright, so basically recently I started studying C as a hobby, and I wanted to create a small program.Everything works fine, but when I make the variable "Age" like this:
int myAge = "14";
printf("My age is%d\n", myAge);
It prints out 1642.
I have tried switching to
printf('My age is%i\n', age);
But it did the same.
I also tested changing the number to a string but it obviously failed, because this isn't Python.
Anybody can help?
Save time, enable all compiler warnings.
Perhaps receive a warning like:
warning: initialization of 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
int myAge = "14"; sets myAge to the address of the string literal "14".
Instead, initialize with an int.
int myAge = 14;
This is a fixed version of your program. Just declaring the age variable as an integer is enough to fix it.
#include <stdio.h>
int main() {
int age = 14;
printf("My age is %d", age);
}
Friendly note:
C is not like Python. Arrays don't work the same, strings don't exist, and programming in C is fundamentally different in every way. I would advise that you definitely take a course rather than trying to teach yourself from scratch.
u should write int myAge = 14 , writting 14 in double quotes means its a string (thx HAL)
We use double quotes when we have string and single quote when we have character but 14 is an integer we should write int myAge=14; or if u want "14" u should write char myAge[2]="14"; then printf("%s",myAge);

increment in while loop doesn't work? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am doing the following while loop, and the line number doesn't get incremented (it's always 0). Why is that?
int main(int argc, const char* argv[])
{
int line_number = 0;
int f = 0;
while (f == 0) {
printf("LINE NUMBER IS %f\n", line_number);
line_number++;
}
return EXIT_SUCCESS;
}
(I realize this is an infinite loop, but I am interested here in why line_number isn't getting incremented.)
With printf, it matters what letter you put after a % sign for variable replacement. If you look at the list of format specifiers, you’ll see that %f is for floating-point numbers. This means it thinks line_number is a float; it doesn’t do the proper conversion because it doesn’t realize it needs to, and instead just reads the same bits as a float.
The way the floating-point format works is complicated, but you’ll stay very close to zero for a very long time. Depending on how fast your computer is and how patient you are, you might or might not see it change if you leave it running for longer.
(Technically it’s even worse than this, as this is undefined behavior; however, this is the most likely outcome.)
Most compilers will have some option to warn you if you use the wrong format specifier; you should probably turn on the default set of compiler warnings so it can tell you about this and other issues.

C programming-In the below program what does '\' means in t[5\] [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
#include <stdio.h>
int main(void) {
int i,t[5\];
for(i = 0; i < 5; i++)
t[i\] = 2 * i;
i = 0;
for(i = 0; i < 5; i++)
i += t[i\];
printf("%d",i);
return 0;
}
What does \ in array means? Thanks in advance.
I found this program in CLA (C Programming Language Certified Associate) sample paper.
The program is incorrect, \] is a syntax error.
A possible explanation is the author had to escape some of the C operators (such as [) to typeset code fragments and he also escaped ] which the word processing software seems to leave alone...
Ignore these \ or replace all occurrences of \] with ].
Note that this is a tricky question, and the programmer who wrote this code should be fired.
Note also that the document in question has other errors. For example Question 11 reads:
What happens if you try to compile and run this program?
#include <stdio.h>
int main(void) {
int t[2\][3\] = { { 3, 2, 1 }, { 1, 2, 3} };
printf("%d", sizeof(t) / sizeof(t[1\][1\]));
return 0;
}
A. the program outputs 6
B. the program outputs 3
C. the program outputs 2
D. the program outputs 4
Ignoring the \], the program has potential undefined behavior as %d expects an int but the value passed to printf() has type size_t.
Questions 13, 14, 15, 17 have a similar problem.
It means:
Christopher Boguslawski, President at the C++ Institute,
had failed to have someone properly check over their sample questions for mistakes.
The code will not run the ways it's written.
One could conjecture that they wanted the \ to be at the end of the line (since it's a valid line continuation character) and forgot to put the line feed carriage return in. While that would fix the problem, it doesn't make sense why they'd do that just before every end bracket.
What makes more sense is they probably did a "find and replace" across their whole document and propagated an error by accident.
In speculation: possibly some typesetter wrote all arrays as: t<|5|> (Or some other configuration that made them go back and replace with proper brackets.)
And then in a fit of laziness they did a Find <| Replace [ Which is ok.
And then Find |> Replace \] Which is not ok.
Which kind of makes sense since the \ and ] are right next to each other on the keyboard. (They probably fat fingered it.)
The fact that the whole document has a \ just before every ] is a smoking gun.
So it's most likely a sloppy Find/Replace that deprecated their whole document.
So it means the \ in t[5\] is an error.
The backslash is not allowed in that case, it's invalid syntax.
You can validate it here at ideone online.
You get the following errors:
prog.c: In function ‘main’:
prog.c:4:13: error: stray ‘\’ in program
int i,t[5\];
^
prog.c:7:10: error: stray ‘\’ in program
t[i\] = 2 * i; i = 0;
^
prog.c:11:15: error: stray ‘\’ in program
i += t[i\];
^
If you want to compile the code without errors you just have to remove the invalid \.
Actually you use the backslash as escape character to use it for example in escape sequences like a new line character '\n' which is described here at wikipedia.

C errors causing huge stress on me [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
I've been playing around with the code below just trying to get it to compile with the Borland compiler (It's the compiler I have to use - I'd much prefer to use GCC on Linux but here we are) but having no luck - can anyone see any obvious flaws?
Code
#include<stdio.h>
#define SIZE 10
float money() {
float wages[SIZE], rise, total; // where i is initaliser
float percent = 0.2;
int i = 0, j;
for(i = 0; i<SIZE; i++) {
wages[i] = j; // Initializing each element seperately
}
printf("Please enter the wages for each staff member\n");
scanf("%d*%c", &wages[i]);
rise = wages[i] * percent;
total = rise + wages[i];
printf("The new wage is $%f and appears in the %d array slot\n", total, j);
return(0);
}
int main() {
money();
return(0);
}
Compiler output
Warning W8004 payrise.c 8: 'i' is assigned a value that is never used in function money
Warning W8065 payrise.c 23: Call to function 'money' with no prototype in function main
These are both warnings; in this case the code referred to by the warnings is correct but it could have its style improved. You should be able to run the program even though it showed warnings; since there were no errors. (BTW you should have help files that came with the compiler; these will tell you what the warnings mean if you find the warning text unclear).
The first warning is because you have:
int i = 0;
for (i = 0;
i.e. the first setting of = 0 is redundant because you immediately set it to 0 again.
The second warning is because you did not provide a prototype for money. You should declare the function as:
float money(void)
This makes it be a prototype, which has the effect that the compiler will flag an error if you later try to pass an argument to the function.
However, your code has other bugs which the compiler did not diagnose (or if it did, you didn't let us know).
Firstly you use j without initializing it. You should give it a value before using it.
Secondly, scanf("%d*%c", &wages[i]); is wrong. The format specifier for float is "%f", not "%d*%c". Also , i is out of range at this point (did you mean to have this code inside the loop?)

C concepts on arrays [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
int main(){
int arr[2]={30,40};
printf("%dn",i[arr]);
return 0;
}
I found this question in an examination and the given solution is
40
But I think it should give an error since i is undefined.
Or, may be I am missing something.
Please explain me how 40 is the correct answer?
Thanks in advance.
You are correct, the code is wrong. Likely, it is a typo, and the intent was either to define i or to use 1[arr].
Probably it is an error, since i is not defined.
Also, probably the intention of the exercise is to take advantage of the fact that in C, you can write v[ i ] in order to access the #i element of a vector v, or i[ v ].
Both forms are equivalent.Since v[ i ] is translated as *( v + i ), there is actually not any difference between that and *( i + v ), which is what i[ v ] is translated for. This is not a common use, but is nonetheless valid.
Arrays in C, from Wikipedia
In this specific example, 1[arr] would return the expected answer.
I just wonder why they chose 40 instead of 42.
Hope this helps.
i is probably supposed to be given as 1, either in the spoken part of the examination, or in a part that is missing. As written, the question is of course inapplicable since it doesn't compile.
The real point of the question is to test whether the applicant understands that array[index] is equivalent to index[array] and (presumably) why.
In C array[index] = *(array + index) = *(index + array) = index[array]. Assuming i to be 1 (otherwise behavior is undefined), 1[arr] is equivalent to arr[1] and it contains value 40.
Hmm, let's see shall we...
matilda:~ jeremyp$ cat > foo.c
int main(){
int arr[2]={30,40};
printf("%dn",i[arr]);
return 0;
}
matilda:~ jeremyp$ cc foo.c
foo.c:4:5: warning: implicitly declaring library function 'printf' with type 'int (const char *, ...)'
printf("%dn",i[arr]);
^
foo.c:4:5: note: please include the header <stdio.h> or explicitly provide a declaration for 'printf'
foo.c:4:18: error: use of undeclared identifier 'i'
printf("%dn",i[arr]);
^
1 warning and 1 error generated.
Yes indeed, i is undefined. You either need
int i = 1;
before that statement or it isn't an i, it's a 1. Let's try that...
matilda:~ jeremyp$ cat >foo.c
#include <stdio.h> // Stops the warning
int main(){
int arr[2]={30,40};
printf("%d\n",1[arr]); // Also added a \ so we get a line feed.
return 0;
}
matilda:~ jeremyp$ cc foo.c
matilda:~ jeremyp$ ./a.out
40
That works now.

Resources