I am very new to C programming and having trouble compiling what should be a very simple function. The function, called printSummary, simply takes 3 integers as arguments, then prints some text along with those integers. For example, if hits=1, misses=2, and evictions=3, then printSummary(hits,misses,evictions) should print the following:
hits:1 misses:2 evictions:3
Here is the code I'm using. Thanks in advance for any advice.
#include<stdio.h>
void printSummary(int hits, int misses, int evictions)
{
printf('hits: %d\n');
printf('misses: %d\n');
printf('evictions: %d\n');
}
int main()
{
int hit_count = 1;
int miss_count = 2;
int eviction_count = 3;
printSummary(hit_count, miss_count, eviction_count);
return 0;
}
Compiling this code gives me several warnings, but no errors. When I run the code, I get a segmentation fault. Like I said, I am fairly new to C so there is most likely a simply solution that I am just missing. Thanks in advance for any advice.
Make the below changes .
printf("hits: %d\n",hits);
printf("misses: %d\n",misses);
printf("evictions: %d\n",evictions);
printf has a
int printf(const char *format, ...)
prototype. So in the first argument you can pass format specifiers and in the next provide the actual variables/values to be printed out
errors are:
void printSummary(int hits, int misses, int evictions)
{
/* Name: printf
Prototype: int printf (const char *template, ...)
Description:
The printf function prints the optional arguments under the
control of the template string template to the stream stdout.
It returns the number of characters printed,or a negative value if
there was an output error.*/
printf("hits: %d\n", hits); // don't use ' it is used only for char variable for example: char a = 'c';
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
}
Your printf function is not being called correctly. You have to include the integers needed to print:
printf("hits: %d\n", hits);
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
Read more about the printf function here.
Related
1) I need to create a function that displays the number entered as a parameter. The function has to be able to display all possible values within an int type variable.
2) and prototype should be like void ft_putnbr(int nb); this way
Here is my code,
#include <unistd.h>
void ft_putnbr(int nb)
{
write(1, &nb, 1);
}
int main()
{
ft_putnbr(42);
}
And the result was not integer numbers, it's just like.. asciicode
It showed "*"
What's wrong with my code? Can you correct my code? or suggest more appropriate way?
plus) int main function will be given automatically, so I just have to make prototyped function
Thanks for your help
The reason your code is not working as expected, is because you passing an integer when you supposed to passing a pointer to the write function and the last argument of write should be the length of what you writing to the file descriptor (standard output in your case).
Here is an explanation of C pointers that may help you understand how to use them
https://boredzo.org/pointers/
Here are some resources on the write function.
https://en.wikibooks.org/wiki/C_Programming/POSIX_Reference/unistd.h/write
http://codewiki.wikidot.com/c:system-calls:write
You need to treat as a string before using write, so you could convert it to a string before had or print it digit by digit
Here is how you could approach it
void ft_putnbr(int n) {
char * const str_num = itoa(n);
const size_t len = strlen(str_num)
write(1, str_num, len);
}
You need to build a string representation of the number, otherwise you're printing the binary.
void ft_putnbr(int nb)
{
char nbuf[16];
const int len = snprintf(nbuf, sizeof nbuf, "%d", nb);
write(1, nbuf, len);
}
int s = system("./my_prog 32"); works, but how do I bring in the argument as a variable? int a = 32; int s = ("system %d", a); doesn't seem to work ("too many arguments to function 'system' ".)
The system() function in C takes a single argument of type const char *. That is why your first example works (though, your second example is malformed).
Still, what you want can be achieved using the sprintf() function in stdio.h. int a = 32; char command[80]; sprintf(command, "./my_prog %d", a); system(command);
how do I bring in the argument as a variable?
A common technique is to generate the command string dynamically, with sprintf(). For example:
char command[100];
int a = 42;
sprintf(command, "./my_prog %d", a);
int s = system(command);
I am writing a c program with void main function in code blocks.
I just write return with no value.
The program is as below:
#include<stdio.h>
void main (void)
{
printf ("ali tariq\n");
return;
}
However, in the console window the program returns the value 16 in the console window. "Process returned 16"
I want to know why it is returning this value?
How can i utilize this value in windows using codeblocks?
Thanks
In (hosted) C the main function must return an int (C11§5.1.2.2.1[1]). By declaring it with a return type of void, and not specifying any return value you invoke undefined behaviour. This means the compiler is free to return anything and in your case it turns out to be 16.
You are not free to declare the return type of main as you wish. Why?
BECAUSE YOU DIDN'T WRITE THE CODE CALLING main(). Sorry 'bout the shouting, but someone else wrote that code and placed it in crt0.o or so. Your main() is linked against that code and it can't just return what it wants because that code expects an int. Always. It's already written and compiled. You understand this subtle point?
Because the C Standard says so. See other answer by Kninnug for Chapter and Verse.
In other words, your code invokes undefined behavior and it should be no surprise to find a garbage value where no value was provided.
So you expected a warning from the compiler? The better ones indeed will catch this with the right options. E.g. gcc and clang support -Wmain-return-type.
You should not use void main(), use int main() instead.
The program has undefined behavior. First of all according to the C Standard main without parameters shall be declared like
int main( void )
You declared the function as having return type void. In this case the process that starts the program can not get a valid return code of the program.
Just because a function is declared as void doesn't mean it won't return anything. On the x86, for example, a lot of calling conventions specify that the value in the register EAX after a function call is the return value of the function. So, if you have a C function that is declared void but the machine code for the function changes the value of EAX, that will get treated as the return value for the function.
EVERY "normal" program that terminate execution WITHOUT errors, must return ZERO.
So, your program must be:
#include<stdio.h>
int main (int argc, char *argv[]) // your program may have command line parameters
{
printf ("ali tariq\n");
return 0; // Program terminate with NO ERRORS
}
However there are cases when one program may terminate WITH errors.
Let's suppose this:
#include<stdio.h>
void main (int argc, char *argv[])
{
// program to make a division between two numbers
double a, b, res;
a = b = res = 0.0;
printf ("Enter 1st number: ");
scanf ("%lf", &a);
printf ("Enter 2nd number: ");
scanf ("%lf", &b);
if (b == 0) return 1; // division by '0' then return ERROR (any number != 0)
printf ("%f / %f = %f", a, b, a/b);
return 0; // NO ERROR
}
Now you may ask: «But where is the return value evaluated?
Answer: «By the Operating System.»
One batch file may run your program and read the integer YOU returned in the environment variable 'ERRORLEVEL'
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
I'm making a program that takes a three-digit integer and splits it into two integers. 224 would become 220 and 4. 114 would become 110 and 4.
Basically, you do it with modulos. I wrote what I think should work and the compiler keeps saying that there is a missing parenthesis before the &big but any changes just make more errors happen.
#include <stdio.h>
void split_num(int complete, int *big, int *little){
*little = complete%10;
*big = complete - *little;
return;
}
int main()
{
int complete, big, little;
printf("Give an integer to split: \n");
scanf("%d", &complete);
void split_num(complete, &big, &little);
printf("Num split into 2 is : %d and %d", big, little);
return 0;
}
Take out the "void" in your call to split_num(). It's only used in the function declaration (to signify that it does not return a value), not in actual invocations of it.
The line (in main())
void split_num(complete, &big, &little);
should read
split_num(complete, &big, &little);
remove the void in the line "void split_num". You don't specify return values (void) when just calling a method.
You have an error in the following line:
void split_num( complete, &big, &little );
Remove the void return type and invoke the function like so:
split_num( complete, &big, &little );
The return; statement in the split_num( ... ) function is also unnecessary.