C concepts on arrays [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 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.

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);

C function calculates wrong with pointers [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 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"
]

C stringification: convert constant to integer [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 4 years ago.
Improve this question
I need to convert defined constants to their integer values so I came up with this macro (STR_TO_CONST) for doing so...
#define STRFY_VAL(s) #s
#define STRFY_KEY(s) STRFY_VAL(s)
#define STR_TO_CONST(s) atoi(STRFY_KEY(s))
It works, but I'm wondering if there are any potential problems with it as I've never encountered this macro before despite having searched considerably for something like it.
The reason you never encountered this is that it's utterly pointless, but let's explain by example. Say you have the following:
#define FINALANSWER 42
// ...
int x = 2 * STR_TO_CONST(FINALANSWER);
now, this is semantically no different from:
int x = 2 * FINALANSWER;
That's because preprocessor macros are ultimately just textual replacement happening before you actually compile. Therefore, FINALANSWER is just as good as an integer constant as 42 is.
Your "solution" to a non-existing problem just adds overhead in that it adds a new string constant to your code and an unnecessary function call as well.
I'm wondering if there are any potential problems with it (?)
Yes. Using atoi() to initialize a global results in something like "error: initializer element is not constant"
int x = STR_TO_CONST(123); // error
int y = 123; // no error
int main(void) {
return x + y;
}
Hide warnings. Only 1 line generated a useful warning
"warning: overflow in implicit constant conversion [-Woverflow]"
int main(void) {
int a = STR_TO_CONST(123456789012345); // no warning
int b = 123456789012345; // warning
return a + b;
}
Range issue. With 32-bit int, the below will likely exceed atoi() range resulting in undefined behavior with no warning.
int main(void) {
long long z = STR_TO_CONST(123456789012345);
return !z;
}

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.

Where did i make a mistake in my program i think its a logical error but i cant quite find it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have this program that I wrote, it complies but I don't think it outputs correctly. Did I make a mistake here?
Here's my program:
#include <stdio.h>
void main(void)
{
int loop_counter = -8;
int user_input = 9;
char c1 = '9';
char c2 = 43;
while(loop_counter != 21);
{
printf("%d\n", loop_counter);
printf("%d\n", loop_counter+1);
printf("%d\n", loop_counter+2);
loop_counter = loop_counter + 1;
loop_counter++;
printf("%d\n", loop_counter);
printf("%d\n", loop_counter+1);
printf("%d\n", loop_counter+2);
getchar();
}
printf("loop exit\n\n");
getchar();
}
The biggest problem is probably that you have not articulated what you are hoping the code will do or what you intended the code to do or what you think it does. I am assuming you just need some help so my attempt to do so is below.
Running this through the compiler and interpreting the error messages helps a little.
Right off the bat, the compiler doesn't like your call to main. The compiler offers a suggestion that will successfully fix this error, so just follow the advice (and don't forget to add a
return 0;
statement before you exit main.
Second warning the compiler generates is that you have a semicolon at the end of your while statement. It also tells you how to fix it. Follow the instructions and you should be able to generate an executable.
You will still, however, have problems at runtime. This gets back to what is your intent.
With errors above corrected, your loop_counter variable enters the while loop initialized to -8, increases by 1 on line 19 and again increases by 1 on line 20. A call is made to getchar() but no input is given. Also lines 7, 8, and 9 are not used by your program.
Hope this gives you some direction. :)
The biggest error is
while(loop_counter != 21);
where the trailing ; will make the loop infinite.

Resources