declaration error when compiling code? - c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv) {
int one = atoi(argv[1]);
int two = atoi(argv[2]);
int finally;
finally = func(one,two);
printf("%d",finally);
return 0;
}
int func(int first,int second) {
int counter = 0;
int new = first;
while (counter != second)
new = new*first;
counter += 1;
return new;
}
Im very new to coding so a lot of this might look like nonsense,
So this code is a complicated way of using the power arithmetic operation,5*3 == 125,
so if i type (./a.out 5 3) it should give out 125,
i seem to get this error
extension.c:15:19: warning: implicit declaration of function 'func' is invalid
in C99 [-Wimplicit-function-declaration]
finally = func(one,two);
^
1 warning generated.

Move the function declaration before the main() function / or alternatively leave it where it is and simply add a function prototype before the main().

Related

Passing argument 1 of 'strcmp' makes pointer from integer without a cast. What is a cast?

I am new to coding in the C language. I am trying to make a program that detects when the RobloxPlayerBeta.exe is being run, but upon compiling it says that "passing argument 1 of 'strcmp' makes pointer from integer without a cast".
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int logout();
char retrieve();
int main(){
char value;
while(1){
system("cmd.exe /C tasklist > Tasks.txt");
value = retrieve();
printf("%d\n",value);
int thing;
thing = strcmp(value,"1");
printf("%d",thing);
if (thing == 0){
int x = logout();
}
sleep(10);
}
return 0;
}
int logout(){
system("c:\\windows\\system32\\shutdown /l");
return 0;
}
char retrieve(){
system("cmd.exe /C start C:\\Users\\chall\\Documents\\Ccode\\Logout\\dist\\FindTask\\FindTask.exe");
FILE *f;
f = fopen("Tasks.txt","r");
int number = fgetc(f);
return number;
}
FindTask.exe is an exe made with the following python code:
with open(r"C:\Users\chall\Documents\Ccode\Logout\Tasks.txt","r") as db:
dataset = db.readlines()
for data in dataset:
if(data[:20].strip().lower() == "robloxplayerbeta.exe"):
with open("Tasks.txt","w") as f:
f.write("1")
I would like to know what a cast is and why I need one.
Cast is to tell the system convert data of one type to another type.
Example:
#include <stdio.h>
int main(void) {
int a = 10;
double b = (double)a; /* cast is used here */
printf("%f\n", b);
return 0;
}
In this case you don't need cast. strcmp() is for compareing strings. You should use operators to deal with numbers to compare single character.
Wrong:
thing = strcmp(value,"1");
Correct:
thing = value - '1';

Flexible array in C

Im trying to have an unlimited array in C to store some data. My header file stock.h looks like this
#ifndef STOCK_H
#define STOCK_H
typedef struct {
char* id;
char* descripcion;
int precio;
} tAppliance;
typedef struct {
int cantidad;
tAppliance electrodomestico;
} tElectroStock;
typedef struct {
int size;
int capacity;
tElectroStock *electrodomesticos;
} tStock;
void tstock_init(tStock *stock);
void tstock_add(tStock *stock, tAppliance item, int cantidad);
#endif
My stock.c file
#include <stdio.h>
#include "stock.h"
void tstock_init(tStock *stock) {
stock->size = 0;
stock->capacity = 10;
stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
}
void tstock_add(tStock *stock, tAppliance item, int cantidad) {
if(stock->size >= stock->capacity) {
stock->capacity = stock->capacity * 2;
stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
}
tElectroStock t;
t.cantidad = cantidad;
t.electrodomestico = item;
stock->size++;
stock->electrodomesticos[stock->size] = t;
}
And finally my main function
#include <stdio.h>
#include "stock.h"
int main(int argc, char **argv)
{
tStock t; // Creamos nuestra variable de stock
tstock_init(&t); // Iniciamos el stock
tAppliance item;
item.descripcion = "Television SONY";
item.id = "apeid9";
item.precio = 20;
tstock_add(&t, item, 1);
tstock_add(&t, item, 1);
}
As you can see on my main function I try to add 2 items to tStock. however adding the second item seems to crash the whole applicattion and no idea why.
Enable all warnings, and treat every single one of them as error. That way you could've found the issue with the member not being a pointer that's already been mentioned yourself.
Check the return value of library functions like malloc and realloc for errors and handle them appropriately.
Finally, you'll want to swap these two lines:
stock->size++;
stock->electrodomesticos[stock->size] = t;
Compile with -Wall you'll be warn:
test.c: In function ‘tstock_init’:
test.c:634:5: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
^
test.c:634:32: warning: incompatible implicit declaration of built-in function ‘malloc’
stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
^
test.c: In function ‘tstock_add’:
test.c:640:9: warning: implicit declaration of function ‘realloc’ [-Wimplicit-function-declaration]
stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
^
test.c:640:36: warning: incompatible implicit declaration of built-in function ‘realloc’
stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
Add to stock.c:
#include <stdlib.h>
You must also switch instruction as below:
stock->electrodomesticos[stock->size] = t;
stock->size++;
Otherwise your code is UB when stock->size++ == stock->capacity

Why can't I call my function(C)?

This is part of a program where I call a function that reads components from a ".dat" file and save the input to members of a Struct. When I try calling the function from my main.c it gives various errors depending on what I try. Most notably: conflicting types of 'ReadFile' and too few arguments to function 'ReadFile'. I also get a warning "passing argument from 'ReadFile' makes integer from pointer without cast" and some infos.
This is main.c
#include "MyData.h"
#include "NodalA.h"
#include "FileHandling.h"
#include <stdio.h>
#include "windows.h"
int main(){
ComponentType *CircuitData;
int numComp = 6;
int numEl = 0;
int numNodes = 0;
CircuitData = malloc((numComp)*sizeof(ComponentType));
ReadFile(CircuitData, &numEl, &numNodes);
return 0;
}
This is FileHandling.c:
#include "FileHandling.h"
#include "stdio.h"
void ReadFile(ComponentType *CircuitData, int *numEl, int *numNodes){
numEl = 0;
numNodes = 0;
int index = 0;
FILE *data;
data = fopen("mydata.dat", "r");
if (data == NULL){
printf("Error: \"mydata.dat\" could not be opened");
}
else {
while(!feof(data)){
fscanf(data, "%s, %s, %s, %f", CircuitData[index].name, CircuitData[index].node1, CircuitData[index].node2, CircuitData[index].value);
*CircuitData[index].node1 = extractInteger(CircuitData[index].node1);
*CircuitData[index].node2 = extractInteger(CircuitData[index].node2);
if(*CircuitData[index].node1 > *numNodes)
*numNodes = *CircuitData[index].node1;
if(*CircuitData[index].node2 > *numNodes)
*numNodes = *CircuitData[index].node2;
numEl++;
index++;
}
}
fclose(data);
}
And this is MyData.h
#ifndef MYDATA_H_
#define MYDATA_H_
typedef struct Comp{
char name[5]; //Name of circuit component
char node1[5], node2[5]; //2 nodes
float value[5]; //value
}ComponentType;
#endif /* MYDATA_H_ */
Any help would be appreciated. There are more code but I think this is the most important part.
The ReadFile function name used in the program is the same as a ReadFile function in "windows.h". The error "too few arguments to function 'ReadFile'" is most likely caused by the program trying to call the the function from windows with the wrong arguments. Removing "windows.h" or renaming the function ReadFile to something else solves the problem.

Segmentation fault while processing argv

This procedure should convert a string that contains a set of double numbers separated by comma (e.g. 7.2,9.5,-5.515) to a vector of double type.
void ToDoubleVec(int d,const char* commaSeparated,double *result)
{
int i;
result[0]=atof(strtok(commaSeparated,","));
for(i=1;i<d;i++)
result[i]=atof(strtok(NULL,","));
}
Here is the snippet of program that calls it:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc,char** argv)
{
...
int i,dim=atoi(argv[1]);
double *lower;
lower = malloc(dim*sizeof(double));
ToDoubleVec(dim,argv[2],lower);
...
}
Debugger's output:
40 lower = malloc(dim*sizeof(double));
(gdb) s
42 ToDoubleVec(dim,argv[2],lower);
(gdb) s
ToDoubleVec (d=2, commaSeparated=0x7fffffffe9d3 "2.3,-62.1", result=0x603010) at testPSO.c:11
11 result[0]=atof(strtok(commaSeparated,","));
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff77f56bb in ?? () from /lib/x86_64-linux-gnu/libc.so.6
Why doesn't it work? I was sure that I've allocated enough memory for the array and also parameters seems to be passed correctly.
You can reduce your code to this SSCCE (Short, Self-Contained, Correct Example), which crashes nicely when you leave out #include <string.h> and does not compile cleanly when you add #include <string.h>:
segv.c: In function ‘ToDoubleVec’:
segv.c:8:5: warning: implicit declaration of function ‘strtok’ [-Wimplicit-function-declaration]
segv.c:8:20: warning: initialization makes pointer from integer without a cast [enabled by default]
segv.c:14:20: warning: assignment makes pointer from integer without a cast [enabled by default]
Code:
#include <stdlib.h>
//#include <string.h>
static void ToDoubleVec(int d, const char* commaSeparated, double *result)
{
int i;
result[0] = atof(strtok(commaSeparated, ","));
for (i = 1; i < d; i++)
result[i] = atof(strtok(NULL, ","));
}
int main(void)
{
int dim = 2;
double *lower = malloc(dim*sizeof(double));
char arg[] = "7.2,9.5,-5.515";
ToDoubleVec(dim, arg, lower);
}
Passing the return value from a function such as strtok() which can return a null pointer directly to a function such as atof() which does not tolerate null pointers is foolhardy; it leads to crashes. If everything is correct, you'll be OK; if not, you'll crash and burn.
The unchecked memory allocation is a similar problem; you didn't even check that dim was non-zero (and non-negative) before doing the memory allocation in the original.
#include <assert.h>
#include <string.h>
#include <stdlib.h>
static void ToDoubleVec(int d, char *commaSeparated, double *result)
{
int i;
char *number = strtok(commaSeparated, ",");
if (number != 0)
{
result[0] = atof(number);
for (i = 1; i < d; i++)
{
number = strtok(NULL, ",");
if (number != 0)
result[i] = atof(number);
}
}
}
int main(void)
{
int dim = 2;
double *lower = malloc(dim*sizeof(double));
char arg[] = "7.2,9.5,-5.515";
assert(lower != 0);
ToDoubleVec(dim, arg, lower);
}
You could — and in one version of the code I did — add error printing to report if the tests on number failed. But the crash is caused by the implicit declaration of strtok() as returning int and not char *.
I have tried to compile your code, and the compiler warned me that strtok() takes as input a char* and not a const char*. Then I have tried this code, and it is working correctly:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void ToDoubleVec(int d, char* commaSeparated,double *result);
int main(int argc,char** argv)
{
int i,dim=atoi(argv[1]);
double *lower;
lower = malloc(dim*sizeof(double));
ToDoubleVec(dim,argv[2],lower);
for (i=0; i<dim; ++i) {
printf("%f\n", lower[i]);
}
return 0;
}
void ToDoubleVec(int d, char* commaSeparated,double *result)
{
int i;
result[0]=atof(strtok(commaSeparated,","));
for(i=1;i<d;i++)
result[i]=atof(strtok(NULL,","));
}
So try to change const char* to char*, and check the input you pass to your program, maybe it is not correct and this could be the problem.

c error :expected expression before 'int'

this is my demo .
#include <stdio.h>
int sqsum(int a, ...)
{
va_list list;
int b = 0,n = a;
va_start(list,a);
while(n > 0)
{
b = b+n*n;
n = va_arg(list,int);
}
va_end(list);
return b;
}
int main(int argc,char **argv)
{
printf("%d\n",sqsum(1,2,3,-1));
return 0;
}
then I compile this demo , it occurs this error ,I donot know this error mean.
If you did not include #include <stdarg.h> and it does not look like you did, then that would explain the error you are seeing, otherwise the program looks correct. If I do not include that header these are the errors I see using gcc:
In function ‘sqsum’:
13:29: error: expected expression before ‘int’

Resources