Reputation: 31
How can I call this convert
function using command line and from argument 2 onwards start converting the strings to int and store in an array?
#include <stdio.h>
int main (int argc , char* argv[])
{
int i;
if (argc < 2)
{
printf("Error: Less than two arguments\n");
}
else
{
for(i=0; i<argc; i++)
{
printf("[%d] : %s\n", i , argv[i]);
}
}
return 0;
}
Function in the same directory but in a separate C file:
void convert ( char* parray[] ,int array[] )
{
int i;
printf("The converted array = ");
for (i=0; i< LENGTH; i++)
{
array[i] = atoi(parray[i]);
printf(" %d" , array[i]);
}
printf("\n");
}
Upvotes: 0
Views: 251
Reputation: 1702
Create a module, have the declarations in a separate file, and the implementations in a separate.
functions.h:
#ifndef FUNCTIONS_H /* include guard */
#define FUNCTIONS_H
void convert(char *parray[], int array[], int length);
#endif
functions.c:
#include "functions.h" /* include your header with the declarations */
#include <stdio.h>
#include <stdlib.h>
void convert(char *parray[], int array[], int length)
{
int i;
printf("The converted array = ");
for (i = 0; i < length; i++)
{
array[i] = atoi(parray[i]);
printf(" %d", array[i]);
}
printf("\n");
return;
}
main.c:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, *arr = NULL;
if (argc < 2)
{
printf("Error: Less than two arguments\n");
}
else
{
arr = malloc((argc - 1) * sizeof(int)); /* array can be static too */
if (arr == NULL)
{
exit(EXIT_FAILURE);
/* handle error */
}
convert(&argv[1], arr, argc - 1);
free(arr); /* free when you exit */
}
return 0;
}
Compilation:
clang -c functions.c && clang main.c functions.o
OR
clang functions.c main.c
Output:
$ ./a.out 15 20 -90 18 20 20 8 8 8 81
$ The converted array = 15 20 -90 18 20 20 8 8 8 81
Upvotes: 0
Reputation: 504
You can compile both files into the same executable, e.g like:
gcc -o main main.c convert.c
To use the function in convert.c
in main.c
, you will have to declare the function before you define the main()
function, like this:
#include<stdio.h>
void convert ( char* parray[] ,int array[] );
int main (int argc , char* argv[])
{
// your code ..
//you may now use the convert function inside the main function
convert(param1, param2);
}
Alternatively, you could create a header file for convert.c
, called convert.h
, like this:
#ifndef CONVERT_H
#define CONVERT_H
void convert ( char* parray[] ,int array[] );
#endif
Then, you could include the headerfile in the main file like this:
#include<stdio.h>
#include "convert.h"
int main (int argc , char* argv[])
{
// use convert here somewhere
convert(param1, param2);
}
Upvotes: 1