int i,*ip;
main()
{
i=5;
ip=&i;
*ip=&ip,printf("%d",i);
}
Why does this code "prints" nothing ? it actually works and doesnt give an error.
edit : Actually this code prints something like 635435 which ,I think, may be the address of ip but when ı use -pedantic-errors flag this give me an error so what should I say about the code ? this prints the address of ip or gives an error.
The statement *ip=&ip is not correct as first *ip=&ip is performed and *ip means 5 and that 5 got replaced with address of ip. It should be
ip = (int*)&ip;/* need to typecast as you are assigning address of pointer
to pointer variable which is not advisable */
your code looks like
int i,*ip;
int main(void) { /* side note use int main() instead of just main() */
i=5;
ip=&i;
ip=(int*)&ip,printf("%d\n",i);
return 0;
}
Also use int main(void) instead of just main() as C spec says
It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local
to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
Related
I am learning C and I am not used to pointers and the way C handles strings. I am trying to create a program that accepts multiple command line arguments and assigns them to variables so that I can later use them. I can get the program to accept the first argument and assign it as a int. But when I try to accept the second argument I get a SEGMENTATION FAULT. I have tried testing by removing the second variable (service) and then assigning port to argv[2] and it doesn't work. It is something about accepting the second argument that the compiler does not like but I am not able to figure it out.
#include <stdio.h>
int main(int argc, char *argv[]) {
int port = atoi(argv[1]);
char service = argv[2];
return 0;
}
When you write char service = argv[2];, you are assigning a char pointer to a char. You know argv is a char pointer array, because you define it as char *argv[]. Fix by just adding char *service = argv[2];
So your rewritten code could look like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Requires more arguments");
return 1;
}
int port = atoi(argv[1]);
char *service = argv[2];
printf("%s", service); //From edit
return 0;
}
You may want to add a check for the value of argc (i.e. argc >= 3), since it will seg fault if there aren't three arguments.
Edit (response to comment):
To print the service, use:
printf("%s", service);
The %s specifies you will print a string of characters (char *) and you simply use service, because you need to specify the pointer.
Edit 2:
If you don't add #include <stdlib.h>, you will receive something along the lines of "warning: implicit declaration of 'atoi' is invalid in C99", which may also produce an error depending on your compiler settings.
My textbook mentions: There must be at least one statement in the executable part of main function.
1)
#include <stdio.h>
void main(){ int c; }
2)
#include <stdio.h>
void main(){ int c; c=0; }
The above two codes result in runtime error.
3)
#include <stdio.h>
void main(){
int c; c=5; printf("%d",c); }
The above code runs fine. What is the possible reason?
First,
1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters: int main(void) { /* ... */ } or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
C 2011 Online Draft, §5.1.2.2.1 Program Startup
Unless your compiler documentation specifically lists it as a valid signature, using void main() leads to undefined behavior, which may be where your runtime errors are coming from.
Secondly, the current C standard does not require that main contain any executable statements.
#include <stdio.h>
#include <string.h>
struct students{
char name[50];
int age;
int height;
};
int main(int argc, char **argv)
{
struct students manoj;
strcpy(manoj.name, "manojkumar");
manoj.age = 15;
displaymanoj(&manoj); //print testing \n , name , age
return 0;
}
void displaymanoj(struct students *ptr) {
printf("Testing...............DEBUG\n");
printf("%s\t%d\n", ptr->name,ptr->age);
printf("END OF TEST: SUCESS -manoj-");
}
I am learning C and it's working where is use pointer to point to structure variable. I am getting the correct output when I run the program. Just that my Geany IDE giving out some message which I would like to know why.
My Compiler Message as below :
You must declare the functions before calling them.
So your program should look something like
// Includes
// Structure
// Function prototype declaration
// This was what you were missing before
void displaymanoj(struct students *ptr);
int main(int argc, char **argv)
{
...
}
void displaymanoj(struct students *ptr) {
...
}
Since you have the definition of displaymanoj() isn't seen when you call it from main(), compiler implicitly declares one with return type int
which conflicts with the actual one. Note that the implicit declaration has been removed since the C99 standard and is no longer valid.
To fix it:
1) Either move the function displaymanoj() above main()'s definition or
2) Do a forward declaration of displaymanoj().
I've written a code that sums up integers brought in from the command line:
#include <stdio.h>
int main(int argc, int* argv[]) {
int i, s=0;
for (i=1;i<argc;i++)
s=s + *argv[i];
printf("Sum: %d\n", s);
return 0;
}
The best part is, it passes the gcc compiling process, but when I actually run it and insert the numbers, the result seems I somehow breached the range of int.
It seems that you are compiling your code in C89 mode in which s is taken as int by default by compiler. s is uninitialized therefore nothing good could be expected. If fact it will invoke undefined behavior.
Note that argv[i] is of char * type (change your main signature) and you need to convert it to int before adding it to s.
The 2nd argument of main should be either of type char** or of type char*[] and not int*[]. So, *argv[i] is of type char. Instead of getting each character, you can get each string(argv[i] which is of type char*) and then extract the number from it and assign it to a variable, say num. This can be done by using the sscanf function:
#include <stdio.h>
int main(int argc, char* argv[]) { //int changed to char here
int i, s=0,num;
for (i=1;i<argc;i++)
if(sscanf(argv[i],"%d",&num)) //if extraction was successful
s=s + num;
printf("Sum: %d\n", s);
return 0;
}
Assuming you have s initialized properly as shown below.
Along with this the prototype of your main() should be as shown below inorder to get the command line arguments.
int main(int argc, char **argv)
{
int s =0;
// Check for argc matches the required number of arguments */
for(i=1;i<argc;i++)
s=s + atoi(argv[i]); /* Use atoi() to convert your string to integer strtol() can also be used */
printf("%d\n",s);
return 0;
}
PS: Using uninitialized variables lead to undefined behvaior
This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 8 years ago.
I understand why C requires a main function to begin the execution of a program, but of the now three books I've read entirely or in portion, none has explained why programs begin by declaring main as int, or with an argument of void:
int main(void)
can someone tell me what the purpose of this is?
The return value of main() is used to indicate success or failure to its parent process. More generally, it can be used to communicate back specific statuses as well, though C doesn't define those.
If main() returns 0 or EXIT_SUCCESS, then the program was successful. EXIT_FAILURE or non-zero, then it failed.
The void in the parameter list simply says that it takes no arguments. This is because of a (mis)feature of C which allows you to declare a function without fully specifying the paramters it takes. A function declared int func(); can be called with any number of parameters, but int func(void); can only becalled with zero.
Example
on linux,
two trivial programs:
$ cat ret0.c
int main (void) { return 0; }
$ cat ret42.c
int main (void) { return 42; }
Then in `bash` we can look at
$ ./ret0 ; echo $?
0
$ ./ret42 ; echo $?
42
So it's possible to use that status when calling your program.
The int return is there to give an error indicator back to the OS. return 0 means no error, all other codes (typically return 1) indicates the program could not finish successfully. Other programs (e.g., shell scripts) can use this error code to determine if your program executed its task, or ran into a problem.
void just means no arguments. It's the same as
int main()
{
/* program */
}
but more explicit.
A program can take command line arguments, in which case main must be defined as
int main(int argc /* number of arguments */, char *argv[] /* arguments)
{
/* program
}
Any good book on C should explain this.
First off let us forget about main. In C(not C++) if you define a function with no parameters like this
int f(){ return 0;}
It is legal to call such a function with any number of arguments:
int a = f(); /* legal */
int a = f("help", 1, 2.0); /* legal */
If you want your function f to only work with exactly no arguments you can amend it like this:
int f(void){return 0;}
int a = f(); /* legal */
int a = f("help", 1, 2.0); /* not legal as it has too many parameters */
The same thing applies to main() and main(void) . In most cases in the reasonable world most people would never care however I have encountered legal code that calls main within the program.
So declaring main like:
int main() {
/* Do a bunch of stuff here */
}
Allows for code elsewhere in your program to do this:
main();
main(1,2,3,4);
By declaring main(void) you add a compiler check that prevents the latter example main(1,2,3,4) from compiling.
Like any other function in C, main is also a function. Thus it has a return type and can
accept arguments.
int main(void)
Here int is the return type of main. Many people still use 'void' because they do not
update themselves with the current language standards. haccks's answer mentions about
the latest standard specifying the signature of main function.
Its general and good practice to have int as main's return type as it tells the parent process of main about the termination (success / failure) of the program.
Like any other function main is also capable of accepting arguments, but with an exception, i.e. the arguments to main are given before the execution of program starts. These are called "command line arguments".
main can accept arguments in two ways :
1. int main(void)
or
int main()
2. int main(int argc, char *argv[])
or
int main(int argc, char **argv)
The first one says that main is not expecting any arguments where as the second declara-
-tion expects the user to provide command line arguments to main.
Note : main should take either 0 or 2 arguments. If you try to give any number of
arguments other than these then it gives the following warning when you compile your code
warning: ‘main’ takes only zero or two arguments [-Wmain]
Edit : The above warning is displayed if you are using gcc.