main arguments and functions in c [closed] - c

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 9 years ago.
Improve this question
#include <stdio.h>
int multiply(int n){
int doenstwork = n * 2;
return doesntwork;
}
int main(int argc, char *argv[]){
int n;
n = atoi(argv[1]);
return multiply(n);
}
I compile but when i run it with an argument I see nothing. Compiled it with gcc -std=c99 filename.c -g.

With the updated code in your question, you have several problems:
You have a typo: you declare a variable doenstwork, but then you try to refer to doesntwork.
Since you say you're able to compile and run your program, what you posted is obviously not the same as what you're actually running. Always copy-and-paste your exact code. If you re-type it, you'll make mistakes like this, and those of us trying to help you can't tell the difference between mistakes you made entering the code in your question and mistakes that are actually in the code you're compiling and running.
The value returned from main is the status of your program, not its output. On Unix-like systems, all but the low-order 8 bits of this value are ignored, so this is not a good way for your program to return detailed information.
Once I corrected the typo, I was able to use your program:
$ gcc c.c -o c
$ ./c 7 ; echo $?
14
but it works only for a small range of values:
$ ./c 1000 ; echo $?
208
The status of a program is used to indicate whether it succeeded or failed, and possibly to return a small amount of information about why it failed. Returning a value of 0 denotes successful execution; returning EXIT_FAILURE (defined in <stdlib.h>) denotes failure. On Unix-like systems, usually EXIT_FAILURE == 1; sometimes a value like 2 is used to denote a different kind of failure. For example, grep returns a status of 0 if a match was found, 1 if no match was found, and 2 if something else went wrong (such as a malformed regular expression or a missing file).
To get information out of a program, the simplest way is to print that information in text form to standard output. You can replace
return multiply(n);
by
printf("%d\n", multiply(n));
You can add a return 0; after that; as of C99 it's not required, but it's not a bad idea to be explicit.

You don't define the variable "doesntwork". This shouldn't compile.
You don't end your function "multiply" with a closing bracket. This shouldn't compile.
You don't include a function prototype for the function "multiply". This shouldn't compile.
If your IDE is so lazy that it will compile this then how do you know that it "didn't work"? Maybe it returned some int to the OS.

Actually Billy Bob is correct. Different IDEs and compilers require different levels of strictness. Full ANSI/ISO compliance, requiring prototypes, etc. can save you a lot of trouble. Your compiler SHOULD require a prototype.
The line:
n = atoi(argv[1]);
is suspicious as well because in C arrays are indexed from zero so the first item in your array should be argv[0].

Related

Why I am getting this output?output = 012345 [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 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for ( ;i<=5;i++)
{
printf ("%d",i);
}
}
Why I am getting this output? output = 012345
I did not expecting any output. because as i didnt intilise i, so from where he is going to start?
if i will be intilise by a undefined value, why I am getting the same output as many times i run the code?
int i;
i is uninitialized and holds an indeterminate value. 0 is one of the many values it can contain.
for ( ;i<=5;i++)
In both i<=5 and i++ you read i that has an indeterminate value. The compiler is allowed to assume that you never do that and may produce assembler code that does anything. The program therefore has what is called undefined behavior.
printf ("%d",i);
Here you print i whatever it may be. If i happened to contain 0 when you left it uninitialized - and if the compiler was "kind" enough to let your failure to initialize i through without producing an executable that crashes (or worse), then the loop will step i from 0 to 6. When it reaches 6, the condition, i<=5, will be false and the loop will end. Only for the values when i is less than, or equal to, 5 will printf ("%d",i); be reached.
Note that the program may do different things when you run it multiple times because it has undefined behavior. i may suddenly be -98723849 when you run the program and then your loop will print the values from -98723849 up to 5.
I did not expecting any output. because as i didnt intilise i, so from where he is going to start?
As mentioned - the program could do just about anything because you didn't initialize i and then read from it. In your case, it seems i contained a 0 and that the program appears to behave as-if you initialized it to 0. Again, this is "pure luck" - no matter how many times in a row it displays the same behavior.
if i will be intilise by a undefined value, why I am getting the same output as many times i run the code?
Because the program has undefined behavior. It may repeat the same thing over and over again for many years. It's a ticking bomb that may suddenly explode one day.

Errors using fclose() [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 4 years ago.
Improve this question
I have a section of code that fails when I try to use fclose to close an output file. The code looks as follows:
void WriteArrayForCheck(int numLines, double **Array) {
char outFile2[300];
sprintf(outFile2, "OutputArray.txt");
FILE *outputFile2;
outputFile2 = fopen(outFile2, "w");
int incRow;
for (incRow = 0; incRow < numLines - 1; incRow++) {
fprintf(outputFile2, "%lf,%lf,%lf\n",
Array[incRow][1], Array[incRow][2], Array[incRow][3]);
}
fclose(outputFile2);
}
I end up with an error related to my executable that says:
free(): invalid next size (normal): 0x0000000001ce1710 ***
and a whole bunch of other stuff that doesn't make sense... The ironic thing is if I comment out the line related to fclose, then the program does not crash and runs perfectly fine... I have not had this issue before. I am sure that my matrices are incremented properly as well. PLease let me know what you think.
The code as posted does not seem to have an obvious problem.
Note however that:
You should always check the return value of fopen() and report failure instead of risking undefined behavior by passing NULL to fprintf and/or fclose.
You should simplify the first few statements as FILE *outputFile2 = fopen("OutputArray.txt", "w");
If you do something more complicated to compute the filename, post it as the problem may lie in seemingly harmless code that you omitted.
The fprintf conversion specifier for double is %f, the l modifier is useless and ignored in this context. It is required in fscanf() to distinguish between float and double, but not needed in fprintf because float values are always passed as double to variable argument functions.
The index values 1, 2 and 3 might be incorrect, arrays are 0 based in C.
Stopping the loop at incRow < numLines - 1 is unexpected too, why omit the last row of the matrix? If you really mean it, a comment would be helpful to clarify why.

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 running same program twice in LINUX [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am wondering if it is possible to run same program twice, and every time it does something different. For instance I have two programs one that writes with fifo pipes and one that reads from it. So there are programA.c and programB.c (simple program, just sending some integers).
But I would like to run it like that:
./program & sleep 1; ./program
So one program would have two operation modes.
Thanks.
Yes, it is possible. You can run a program however many times you want. However, you may need to ensure that two instances of the same program do not contend for the same resources; for instance, if they both write to the same file, unexpected results may occur.
If you want the same program to do two different things (one writing to the fifo and one reading from it) you will have to ensure that the program can determine which action to take. One way of doing this would be to parse command-line parameters (e.g. invoke one as myprog --read and the other as myprog --write. Another would be for the program first to check for the existence of the fifo; if it doesn't exist, it could create the fifo and write to it, and if it does exist it could read from it.
Write your program to accept command line arguments like sed or awk.
Here is a simple example in C:
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 1 ) printf("You passed in zero arguments and your program is named %s\n", argv[0]);
if( argc > 1 ){
int x;
for(x = 1; x < argc; x++)
printf("Argument %d is named %s\n",x, argv[x]); //print multiple arguments
}
return 0;
}
If you compile and run this program with no arguments it will tell you that you didn't pass in any arguments; otherwise, you can pass in as many command line arguments as you like and it will print them back out for you.
The point is that this one program does different things depending on the arguments passed into it.

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