I have this assignment where we expected to write a program that takes
a positive integer number as a command line argument and prints the
smallest prime number bigger than the given number.
The main function shouldn't be edited, however, you may create a
header file for defining needed functions.
So far this is what I came up with, I just can't find out what
is wrong with my program. Help is appreciated.
main function: I can't edit the main function, however, you can create a header
#include "slow-prime.h"
int main(int argc, char *argv[]) {
int num;
int nxt;enter code here
int ret = EXIT_FAILURE;
if (argc < 2) {
printf("error: missing command line argument\n");
goto ERROR;
if (get_number(argv[1], &num)) {
printf("error: %s not a number\n", argv[1]);
goto ERROR;
}
next_prime(num, &nxt);
printf("%d\n", nxt);
ret = EXIT_SUCCESS;
ERROR:
return ret;
}
}
needed functions are created in the slow-prime.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// define true and false
#define true 1
#define false 0
// check whether the numer is prime or mnot
int isPrime(int num){
if (num < 2) {
return false;
}
for (int i = 2; i <= num / i; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// get number
void get_number(char *argv[], int num) {
num = atoi(argv[1]);
}
// loop through the numbers/ and pick the one
void next_prime(int num, int next){
for(int i = 2; i < 80; i++){
if (isPrime(i) == true){
next = i;
if (next > num) {
return exit(0);
}
}
}
}
Error Message:
error
You have:
void get_number(char *argv[], int num) {
and you are calling the function using:
if (get_number(argv[1], &num)) {
You are passing the wrong types for both arguments.
argv[1] is of type char*.
&num is of type int*.
I think you should to use:
void get_number(char *arg, int *num) {
and change the implementation slightly.
void get_number(char *arg, int *num) {
*num = atoi(arg);
}
Also, given that get_number returns void, you cannot use it in the conditional of an if statement. You'll need to change its return type to something else, an int perhaps. In that case, using atoi might not be appropriate. atoi returns 0 when it cannot convert the string to an int. If 0 a valid value for you, then atoi is not a good choice. However, you can use sprintffor all cases.
If 0 is not a valid number, you can use:
int get_number(char *arg, int *num) {
*num = atoi(arg);
return *num;
}
If 0 is a valid number, you can use:
int get_number(char *arg, int *num) {
return (sprintf(arg, "%d", num) == 1);
}
Related
I have to use command line arguments to set up a map for a snake game for my uni assignment. We were not specifically told to use atoi to help convert the command line argument from string to int, However I thought the simple nature of atoi would do the trick. On testing I discovered it is only taking the first digit.
int main(int argc, char *argv[])
{
int isUserInput;
char arg1, arg2, arg3;
arg1 = argv[1][0];
arg2 = argv[2][0];
arg3 = argv[3][0];
isUserInput = checkUserArg(arg1, arg2, arg3);
int checkUserArg(char arg1, char arg2, char arg3)
{
int validation;
int rowMap, colMap, snakeLength;
rowMap = atoi(&arg1);
colMap = atoi(&arg2);
snakeLength = atoi(&arg3);
if ((rowMap < 5) || (colMap < 5) || (snakeLength < 3))
{
validation = FALSE;
}
else if ((rowMap >= 5) || (colMap >= 5) || (snakeLength >= 3))
{
if (snakeLength < colMap)
{
validation = TRUE;
}
else
{
validation = FALSE;
}
}
else
{
validation = FALSE;
}
return validation;
}
User has to enter 3 command line arguments (./file num1 num2 num3). I used atoi to convert the string command line arguments to int, but while testing I printed the numbers back and it won't convert the second digit only the first, e.g 1-9 works, but anything from 10 onwards only shows the first digit.
Any thoughts on why this is?
Cheers.
There are multiple problems in your code:
atoi is only using the first digit because you explicitly extract the first digit and pass it as a char. The function call actually has undefined behavior as &arg1 is the address of a single char, not that of a null terminator C string.
checkUserArg converts the arguments using atoi which has undefined behavior if the value converted exceeds the range of type int. Using strtol is recommended and allows for finer checks.
checkUserArg should return the converted values to the caller via pointer arguments.
the second test in checkUserArg is redundant: if the first test is false, then all 3 comparisons in the second test will be true.
instead of TRUE and FALSE, you should use definitions from <stdbool.h>.
Here is modified version:
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
bool convertArg(const char *arg, int *vp) {
char *p;
long num;
errno = 0;
num = strtol(arg, &p, 10);
if (errno || p == arg || *p != '\0' || num < INT_MIN || num > INT_MAX) {
*vp = 0;
return false;
} else {
*vp = (int)num;
return true;
}
}
int main(int argc, char *argv[]) {
int rowMap, colMap, snakeLength;
if (argc != 4) {
fprintf(stderr, "program needs 3 arguments\n");
return 1;
}
if (!converArg(argv[1], &rowMap) || rowMap < 5) {
fprintf(stderr, "invalid rowMap argument\n");
return 1;
}
if (!converArg(argv[2], &colMap) || colMap < 5) {
fprintf(stderr, "invalid colMap argument\n");
return 1;
}
if (!converArg(argv[3], &snakeLength) || snakeLength < 3 || snakeLength >= colMap) {
fprintf(stderr, "invalid snakeLength argument\n");
return 1;
}
[...]
}
A single character is not a string. A string is an array of characters with null termination at the end.
You should do something like this instead:
bool checkUserArg (const char* arg1, const char* arg2, const char* arg3);
const since we shouldn't modify the args. Now this function can call atoi using the parameters directly.
However atoi is a broken function by design that should never be used, because it does not have well-defined error handling. Using it directly on argv is dangerous. You should always use strtol instead of atoi, it's a safer and more powerful function.
Example:
#include <stdlib.h>
#include <stdbool.h>
int main (int argc, char *argv[])
{
if(argc != 4)
{
// error handling!
}
if(checkUserArg(argv[1], argv[2], argv[3]) == false)
{
/* error handling */
}
...
bool checkUserArg (const char* arg1, const char* arg2, const char* arg3)
{
const char* endptr;
...
rowMap = strtol(arg1, &endptr, 10); // 10 for decimal base
if(endptr == arg1) // if these compare equal, the conversion failed
{
return false;
}
...
return true;
}
I have a problem with casting returned integer value to void pointer. Have tried some options from this site but my problem seems to still haven't been resolved. Although the program compiles with no code errors I'm getting a segmentation fault. Am I blind and are there some mistakes in my code?
#include<pthread.h>
#include<stdio.h>
#include<stdint.h>
int ackermann(int a, int b)
{
if(a==0)
return a+1;
else if(a>0 && b==0)
{
return ackermann(a-1, 1);
}
else if(a>0 && b>0)
{
return ackermann(a-1,ackermann(a,(b-1)));
}
}
int main(int argc, char* argv[])
{
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = ackermann(a,b);
void *ptr = &c;
pthread_t mythread;
if(pthread_create(&mythread, NULL, ptr, NULL))
{
printf("Could not create a thread\n");
}
pthread_exit(NULL);
return 0;
}
As was mentioned in the comments, you're not actually calling the function ackermann in a separate thread. What you are doing is calling the function directly from main, storing the result in an int, and passing a pointer to that int as the third parameter to pthread_create, which is supposed to be a pointer to the function to run.
Right now, ackermann does not have the appropriate signature to be passed to pthread_create. A function that starts a new thread should be declared like this:
void *my_thread_function(void *parameter);
Given that ackermann is called recursively, it would be cleaner to pass a a wrapper function to pthread_create and have that wrapper call ackermann rather than modifying ackermann to match the above signature.
Because you need to pass multiple parameters to your thread function, you'll need to create a struct which contains all the parameters and pass a pointer to that struct to thread function.
You can also store the return value in this struct so that the function which started the thread has access to it.
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
int ackermann(int a, int b)
{
if(a==0) {
return a+1;
} else if(a>0 && b==0) {
return ackermann(a-1, 1);
} else if(a>0 && b>0) {
return ackermann(a-1,ackermann(a,(b-1)));
}
// if none of the above conditions are true, no value is returned
// better check for this
}
struct ackermann_params {
int a;
int b;
int result;
};
void *ackermann_thr(void *arg)
{
struct ackermann_params *params = arg;
params->result = ackermann(params->a, params->b);
return NULL;
}
int main(int argc, char* argv[])
{
struct ackermann_params params;
if (argc < 3) {
printf("invalid number of arguments\n");
exit(1);
}
params.a = atoi(argv[1]);
params.b = atoi(argv[2]);
pthread_t mythread;
if(pthread_create(&mythread, NULL, ackermann_thr, ¶ms))
{
perror("Could not create a thread\n");
exit(1);
}
if (pthread_join(mythread, NULL)) {
perror("join failed\n");
exit(1);
}
printf("result=%d\n", params.result);
return 0;
}
I am trying to code the printf function. The problem is that my code is getting very messy and I need some help to try to make it organized and working (hopefully). I have been told that I should use "array of function pointers" so I tried below (ft_print_it) as you can see but I do not know how to how to structure my code so that I can use a big array of function pointer to put every function like int_decimal_octal and friends. Can you help me on that? Where can I call them from?
Also, I realized the little function below (cast_in_short) is giving me the same result as printf if I write the output with my ft_putnbr. My second question is thus: Can I make my printf work with little functions like this? Thank you so much.
int cast_in_short(int truc)
{
truc = (short)truc;
return (truc);
}
/*
here in the main I noticed that I get the same behaviour
between my putnbr and printf thanks to my little function
cast_in_short. This is the kind of function I want to use
and put into an array of pointer of functions in order
to make my printf work
*/
int main()
{
int n = 32769;
n = cast_in_short(n);
ft_putnbr(n);
printf("\n");
return (0);
}
/* function to launch ft_print_it */
int ft_print_str_spec(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putstr(va_arg(ap, char *));
else
{
ft_nbzero(ap, flag, 0);
ft_putstr(va_arg(ap, char *));
}
return (1);
}
int ft_print_oct(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putnbr(decimal_octal((va_arg(ap, int))));
else
{
ft_nbzero(ap, flag, 1);
ft_putnbr(decimal_octal((va_arg(ap, int))));
}
return (1);
}
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
char *ft_strjoin2(char const *s1, char const c);
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
int decimal_octal(int n) /* Function to convert decimal to octal */
{
int rem;
int i;
int octal;
i = 1;
octal = 0;
while (n != 0)
{
rem = n % 8;
n /= 8;
octal += rem * i;
i *= 10;
}
return (octal);
}
I think the best way to organize your code to avoid the function like your "flag_code" is to use an array of structure. With structure that contain a char (corresponding to the flag) and a function pointer.
For example :
typedef struct fptr
{
char op;
int (*ptr)(va_list);
} fptr;
And instatiate it like that (with { 'flag', name of the corresponding function} ) :
fptr fptrs[]=
{
{ 's', ft_print_nb_spec },
{ 'S', ft_print_nb_up },
{ 0, NULL }
};
Then when you know have char after the % (the flag) you can do something like this :
int i = -1;
while (fptrs[++i].op != flag && fptrs[i].op != 0);
if (fptrs[i].op != 0)
{
fptrs[i].ptr();
}
For exemple if flag = 'S' the while loop will stop when i = 1 and when you call fptrs[1].ptr() you will call the corresponding function in the structure.
I think instead of making your code messy by using function pointers, because in the end you cannot specialize printf function without providing the format, in C there is no function overloading or template functions. My suggestion is to special printf function by type.
// print seperator
void p (int end)
{ printf(end?"\n":" "); }
// print decimal
void pi (long long n)
{ printf("%lld",n); }
// print unsigned
void pu (unsigned long long n)
{ printf("%llu",n); }
// print floating point
void pf (double n)
{ printf("%g",n); }
// print char
void pc (char n)
{ printf("%c",n); }
// print string
void ps (char* n)
{ printf("%s",n); }
Test try here
pi(999),p(0),pf(3.16),p(0),ps("test"),p(1);
Output
999 3.16 test
Another option
In theory you can define polymorphic print function in a struct, in case you can do something like this. I haven't tested this yet.
struct Node
{
enum NodeType {Long,Double,Char,String} type;
union {long l,double d,char c,char* s};
};
void p(Node* n)
{
switch (n->type)
{
case Node::NodeType::Long: printf("%ld", n->l);
case Node::NodeType::Double: printf("%g",n->d);
case Node::NodeType::Char: printf("%c",n->c);
case Node::NodeType::String: printf("%s",n->s);
}
}
My code is giving me a segmentation fault and I can't seem to find what I'm doing wrong:
#include <stdio.h>
#include <string.h>
char find(char name[], char allNames[][10], int length)
{
int i=0;
for (i = 0; i < length; i++) {
if (strcmp(allNames[i],name) == 1) {
printf("%i",i);
return *name;
}
}
return -1;
}
main(){
char allNames[][10] = {"cat","dog","frog","log","bog"};
char name[] = "log";
int length=5;
printf("%s",find(name,allNames,length));
}
I'm really keen to understand all the mechanisms happening here and what I'm doing wrong for tomorrows exam. Thanks for your help!
EDIT: Really Appreciate the answers and information guys! I'm really quite new to C and just getting used to what every thing means. The particular exam question I am looking at is :
(a) The following function is intended to find the string name in the array
allNames. If found, it returns the position of name in the array. If not
found, it returns -1. Modify the code so that it works correctly.
int find(char name[], char allNames[][10])
{
for (i = 0; i < 10; i++) {
if (allNames[i] == name) {
return name;
}
}
return -1;
}
And I'm trying to get a program to work within these parameters. Cheers :)
http://coliru.stacked-crooked.com/a/d400c9a56d732446
#include <stdio.h>
#include <string.h>
char* find(char name[], char allNames[][10], int length)
{
int i=0;
for (i = 0; i < length; i++) {
if (!strcmp(allNames[i],name)) {
printf("%i",i);
return name;
}
}
return NULL;
}
int main(){
char allNames[][10] = {"cat","dog","frog","log","bog"};
char name[] = "log";
int length=5;
printf("%s",find(name,allNames,length));
}
Returning a single char will do you no good if you're trying to return a string. I would also suggest that you return a NULL if you cannot find the string.
Also, include the int before main; this is better style.
The direct reason for your Segmentation Fault here is because the code tried to print the char type with %s(which needs an address value).
void main()
{
char c = 'a';
printf("%s", c); // will cause Segmentation fault here
}
Back to your code, that is
char find(char name[], char allNames[][10], int length)//return char
printf("%s",find(name,allNames,length));
The minimal change to make it work as follows,
1) To return char*
char* find(char name[], char allNames[][10], int length)//return char*
{
int i=0;
for (i = 0; i < length; i++) {
if (strcmp(allNames[i],name) == 0) { // here should 0
printf("%i",i);
return name; // change name* to name
}
}
return NULL; // change to NULL
}
//to print
printf("%s",find(name,allNames,length));
2) to return position value
int find(char name[], char allNames[][10])
{
for (i = 0; i < 10; i++) {
if (allNames[i] == name) {
return i; // here, change to return i
}
}
return -1;
}
//then, you can print like this
printf("find at position: %d",find(name,allNames,length));
//or to print string by
int pos = find(name,allNames,length);
if(pos >= 0)
printf("find the string: %s",allNames[pos]);
This code is wrong on several levels.
gcc -Wall -Wextra reveals:
meh.c:15:1: warning: return type defaults to ‘int’ [-Wreturn-type]
main(){
^
meh.c: In function ‘main’:
meh.c:19:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("%s",find(name,allNames,length));
^
meh.c:21:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
What's up with that? Do you compile with warnings enabled?
I am ignoring the lack of indentation.
#include <stdio.h>
#include <string.h>
char find(char name[], char allNames[][10], int length)
What? How about: char *name, **list, int size)
{
int i=0;
Why set it to 0 here?
for (i = 0; i < length; i++) {
if (strcmp(allNames[i],name) == 1) {
printf("%i",i);
return *name;
Have you read strcmp's manpage? It returns ZERO when a string matches, so this code makes no sense.
*name is of type char, but you don't want to return a char. You want to return a pointer, no?
}
}
return -1;
Well, given that you feed that into %s in printf, what do you expect to hapen here? Normally one would return NULL.
}
main(){
This is obsolete syntax, I don't know where you stole it from. Use 'int main(void)'.
char allNames[][10] = {"cat","dog","frog","log","bog"};
Normally people just return such arrays with a NULL pointer, so that these can be iterated over and there is no need to pass anything about the size.
char name[] = "log";
Why not char *name = "log".
int length=5;
Incorrect. It hardcodes the amount of stored strings in allNames table.
printf("%s",find(name,allNames,length));
}
I want to get a value from a function in other function i think i have to call a function in other function, then call it on main, but how?
void funcA(PEOPLE people[], int *total)
{
FILE *fp;
char line[100];
fp = fopen("example.txt", "r");
if (fp == NULL) {
exit(1);
}
else {
fgets(line, 100, fp); //get a number from the txt
total = atoi(line); //convert to int
}
}
void funcB(PEOPLE people[], int *total)
{
int i;
for (i = 0; i < total; i++) {
printf("%s\n", people[i].name);
}
funcA(people, &total);
}
void main()
{
PEOPLE people[100];
int *total;
funcB(people, &total);
}
What i'm doing wrong? I need the value from total to do cicle for;
First, you should call funcA from funcB like this:
funcA(people, total);
Then, if I understand you correctly, you want to return a value from your function(s). You can do it like this:
int funcA(PEOPLE people[], int *total){
int ret;
// set ret to desired value
return ret;
}
...
int value = funcA(people, total);
After sorting this out, you need to initialize your variables correctly, sort out the naming discrepancies (linha vs line, PEOPLE vs PERSON) and all other issues noted by others.
There are numerous problems here (total is a pointer, for loop on the pointer, never initialized to anything, etc etc).
To answer your question, functions have return types:
int foo(void) {
return 3;
}
int main(int argc, char**argv) {
printf("Foo returned %d\n", foo());
return 0;
}
In this case foo returns int. You return values with the return keyword.
You can also return data in pointers:
void foo(int* c) {
*c = 3;
}
int main(int argc, char**argv) {
int h;
foo(&h);
printf("Foo returned %d\n", h);
return 0;
}
This is helpful if you have multiple values to return.
Oh boy !
First what You are doing right or at least it seems so. You are drawing attention and get points for upvotes, despite the fact, that the code looks like typed in directly to the editor box on the Stackoverflow and never checked with any compiler. Good job :)
Now what's wrong. The list is long but some tips
void main()
{
PERSON person[100];
int *total;
funcB(people, &total);
}
void funcB(PEOPLE people[], int *total);
It would be nice if You showed us the definitions of (probably) structs PEOPLE and PERSON.
In the code we can see, there is no definition of people - the variable you pass to funcB.
You define a pointer to int - total and don't initialize it. Then You pass an address of that pointer to funcB which takes int* not int** as a second argument. Those types are not compatible.
void funcB(PEOPLE people[], int *total)
{
int i;
for (i = 0; i < total; i++) {
printf("%s\n", people[i].name);
}
funcA(people, &total);
}
void funcA(PEOPLE people[], int *total)
You use a pointer in the loop condition instead of the value pointed too. There is no value, because You didn't initialize the pointer in main, but here You have incompatible types in the condition. You pass an address of the pointer to funcA instead of the pointer, like in main.
void funcA(PEOPLE people[], int *total)
{
FILE *fp;
char line[100];
fp = fopen("example.txt", "r");
if (fp == NULL) {
exit(1);
}
else {
fgets(line, 100, fp); //get a number from the txt
total = atoi(linha); //convert to int
}
}
You use an undefined symbol 'linha' - I guess it's a misspelling of 'line'. Then You assign an int to a pointer instead of an int pointed to by that pointer.
Check these:
exit() function exited from your program, not only from function. You can use return; to return from the function.
total is not initialized when you use that. Use funcA(people, &total); line before the for loop in your function funcB.