passing argument 1 of âgetGradesFromFileâ makes integer from pointer without a cast - c

I am writing a program to read a file of records, extract some fields into a VLA’s, sort them using insertion sort, search for a user-specified target using binary search, and print out the result.
Bud I keep getting these errors:
search.c: In function âmainâ:
search.c:57: warning: passing argument 1 of âgetGradesFromFileâ makes integer from pointer without a cast
search.c:19: note: expected âintâ but argument is of type âchar *â
search.c:57: warning: passing argument 2 of âgetGradesFromFileâ makes pointer from integer without a cast
search.c:19: note: expected âchar *â but argument is of type âintâ
search.c:57: warning: passing argument 3 of âgetGradesFromFileâ from incompatible pointer type
search.c:19: note: expected âint *â but argument is of type âchar *â
search.c:57: warning: passing argument 4 of âgetGradesFromFileâ makes integer from pointer without a cast
search.c:19: note: expected âintâ but argument is of type âint *â
search.c:57: warning: passing argument 7 of âgetGradesFromFileâ makes pointer from integer without a cast
search.c:19: note: expected âchar *â but argument is of type âintâ
search.c:57: error: too many arguments to function âgetGradesFromFileâ
search.c:59: warning: passing argument 1 of âprintArrayâ makes integer from pointer without a cast
search.c:38: note: expected âintâ but argument is of type âchar *â
search.c:59: warning: passing argument 2 of âprintArrayâ makes pointer from integer without a cast
search.c:38: note: expected âchar *â but argument is of type âintâ
search.c:62: error: expected expression before âintâ
search.c:62: error: too few arguments to function âinsertionSortâ
search.c:67: warning: comparison between pointer and integer
search.c:68: warning: comparison between pointer and integer
search.c:68: warning: comparison between pointer and integer
search.c:69: warning: passing argument 3 of âbinarySearchâ makes integer from pointer without a cast
search.c:33: note: expected âintâ but argument is of type âint (*)[60]â
search.c:69: error: too few arguments to function âbinarySearchâ
search.c:73: error: expected â(â before â{â token
Any help with these errors is appreciated!!
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void getGradesFromFile(int size,
char line[],
int studentI_D[],
int test1,
int test2,
int test3,
char grades[]);
void insertionSort(char list[],
int last);
void binarySearch(int size,
int studentID[],
int target,
char* locn);
void printArray(int size,
char list[*],
int studentI_D[*],
int test1,
int test2,
int test3,
char grades[*]);
int main(void)
{
char grades[60];
char str[60];
int size = sizeof(str) / sizeof(str[60]);;
int studentID [60];
char letter;
int exam1, exam2, exam3;
getGradesFromFile("grades.csv", size, str, studentID, exam1, exam2, exam3, grades);// function call
printf("The original numbers are:");
printArray(str, size, studentID, exam1, exam2, exam3, grades);
printf("\n\n");
printf("The sorted numbers are:");
insertionSort(int size, studentID, grades);// inscertion sort function call
printf("\n\n");
printf("Enter student ID and -1 to quit");
scanf("%d", studentID);
while (studentID != -1){
if (studentID > 99999 && studentID < 1000000){
binarySearch(size, studentID, &studentID);
}
else if {
printf ("Error and enter again [100000, 999999] and -1 to quit");
}
exit;
}
return 0;
} // end of main
void getGradesFromFile(int size,
char line[],
int studentI_D[],
int test1,
int test2,
int test3,
char grades[])
{
FILE* pData;
int i = 0;
if ((pData == NULL) {// opens file grades.csv
fprintf(stderr, "Error opening file %s.\n");// error handling statement
exit(1);
}
while (fgets(line,sizeof(line), pData) != NULL){
sscanf(line, "%25s, %d, %d, %d, %c", studentID[i], &test1, &test2, &test3,
grades[i]);
i++;
}
}
if fclose(pData) {
fprintf(stderr, "Error closing file %s.\n", filename);// close file
exit(2);
}
}
void insertionSort(int length, int studentID[], char grades[])
{
int i, key, key1, j;
for (i = 1; i < n; i++)
{
key = studentID[i];
key1= grades[i];
j = i-1;
while (j >= 0 && studentID[j] > key)
{
studentID[j+1] = studentID[j];
grades[j+1] = grades[j];
j = j-1;
}
studentID[j+1] = key;
grades[i+j] = key1;
}
}
void binarySearch(int size, int student[], int target, char *locn)
{
int first = 0;
int last = size - 1;
int mid;
bool found = false;
while (first <= last) {
mid = (first + last) / 2;
if (target > list[mid]) {
first = mid + 1;
} else if (target < list[mid]) {
last = mid - 1;
} else {
*locn = mid;
found = true;
break;
}
}
return found;
}
void printArray(int size,
char A[size],
int studentI_D[size],
int test1,
int test2,
int test3,
char grades[size])
{
for (int i=0; i<size; i+=4) {// prints the array in four lines
printf("\n");
for (int j=0; j<4; j++) {
printf("%10.2f ", A[i+j]);
}
}
}
void flushScanf(void)
{
char c;
while((c = getchar() != '\n' && c != EOF)
;
}

void getGradesFromFile(int size,
char line[],
int studentI_D[],
int test1,
int test2,
int test3,
char grades[]);
size is int type but you are passing "grades.csv" which is a string hence its address will be paased and hence it becomes pointer.
line[] is an array hence a pointer, You are passing size of type int
studentI_D[] is an array of type int. you are passing str of type char and so on....
Your function declaration and definition got 7 parameters but you are passing 8 parameters and hence resulting in error.
You need to check rest yourself. These are silly errors.

Related

How can I pass an array of structures to another function

I am trying to pass an array of structs as pointer in another function. But the compiler just refuses.
I build up this code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Values{
char timestamp[21];
char temperature[2];
int tmp;
};
char *readString(char out[], FILE *fp){// Reading and storing the input values, out = the string that this func returns
int ch, i;
while(EOF!=(ch=fgetc(fp)))
if(ch == '"') break;
for(i=0;EOF!=(ch=fgetc(fp));++i){
if(ch == '"') break;
out[i] = ch;
}
out[i]='\0';
return out;
}
void printValues(struct Values * v, int i){ //just a printing method, for printing the values, i = the amount of values I have
int j;
for(j=0; j<i; j++){
printf("%s \t : \t %s \t :\t %d \n\n", v[j]->timestamp, v[j]->temperature, v[j]->tmp);
}
}
void makeTmpIntegers(struct Values values[], int i){ //making temperatures integers so I can use them in sorts, i = the amount of values I have
int j;
for(j=0; j<i;j++){
values[j].tmp = atoi(values[j].temperature);
}
}
int main(void){ //The beginning of the programm, what did you expect?
struct Values values[8223];
FILE *file = fopen("hum.txt", "r" );
int i=0; //the number of every stored value (for the timestamps)
int k=0; //the number of every stored value (for the temperatures)
if (file != NULL ){
char tempString [21];
int flag = 1;
while(*readString(tempString, file)){ //if the readStrinf outputs "/0" == "" (end of FILE)
if(flag == 1){strcpy(values[i].timestamp, tempString); flag++; i++;}
else if(flag == 2){strcpy(values[k].temperature, tempString); flag--; k++;}
}
fclose(file);
}
makeTmpIntegers(values, i);
printValues(&values, i);
return 0;
}
I know for a fact that I can pass the struct from a function to another (it works fine that way), but I want to pass pointers (memory reasons).
I have been trying to do it at the function called printValues()
In this case the compiler does not compile. This is the message I get:
In function 'printValues':
24 46 [Error] invalid type argument of '->' (have 'struct Values')
24 63 [Error] invalid type argument of '->' (have 'struct Values')
24 82 [Error] invalid type argument of '->' (have 'struct Values')
In function 'main':
53 17 [Warning] passing argument 1 of 'printValues' from incompatible pointer type
21 6 [Note] expected 'struct Values *' but argument is of type 'struct Values (*)[8223]'
Plus if I initialize the function like this: void printValues(struct Values * v[], int i)
It does compile but it does not prints the values at all
I know that the correct way to read an integer from a txt file, is not like this but I couldn't figure something else out
This is OK:
struct Values{
char timestamp[21];
char temperature[2];
int tmp; };
So are these two function signatures:
void printValues(struct Values * v, int i) { ... }
void makeTmpIntegers(struct Values values[], int i) { ... }
This is WRONG:
v[j]->timestamp, v[j]->temperature, ...
Substitute:
v[j].timestamp, v[j].temperature, ...
ALSO:
Change printValues(&values, i); to printValues(values, i);
I haven't checked carefully for any other errors, but this should get you moving in the right direction...
ADDENDUM:
In both of the examples above, printValues(struct Values * v, int i) and makeTmpIntegers(struct Values values[], int i), you're ALREADY "passing by pointer". You just need to fix your syntax, as in my examples.
As Oppen said below:
Also, note that passing an array argument in C is functionally
equivalent to passing a pointer, no copy is involved, so I'm not sure
what memory reasons stop you from just passing the array of structs
directly...

While executing this program the char function does the returning the variable.i dont know why?

Here in the program, findnumber function getting array elements and the value to be searched via STDIN.The output which i expected is if the value equals any one of the element in the array it displays YES or else NO.
#include<stdio.h>
#include<string.h>
char findNumber(int,int[],int);``
int main()
{
int n,a[10],s;
char c;
c=findNumber(n,a,s);
printf("%s",c);
return 0;
}
char findNumber(int arr_count, int arr[], int k)
{
int i=0,j,flag;
char y="YES";
char N="NO";
scanf("%d",&arr_count);
scanf("%d",&k);
for (j=0;j<arr_count;j++)
{
scanf("%d",&arr[j]);
}
while(i<arr_count)
{
if(arr[i]==k)
flag=1;
i++;
}
if(flag==1)
return y;
else
return N;
}
warning: initialization of 'char' from 'char *' makes integer from
pointer without a cast [-Wint-conversion]
char y="YES";
warning: initialization of 'char' from 'char *' makes integer from
pointer without a cast [-Wint-conversion]
char N="NO";
A string constant like "YES" or "NO" is an array of characters, not a single character, so you can't store them in a char.
You need to declare y and n as char * so they can point to the string constant and change the return type of the function accordingly.
const char *findNumber(int arr_count, int arr[], int k)
{
const char *y="YES";
const char *N="NO";
...

Arrays and Structs

I am taking an online college course introducing C and am completely stumped on my latest project. My professor to research online for the errors but the examples don't seem to match. I started the program on Visual Studio 2013 and now have moved to Code::blocks from the professor's instruction.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct flightRec { // declare a struct to match the format of the binary data
char FlightNum[7];
char OriginAirportCode[5];
char DestAirportCode[5];
int timestamp;
} flightRec;
int flightCmp(const void *a, const void *b) // comparison function of DestAirportCode to ascending order
{
const flightRec *p1 = (flightRec *)a;
const flightRec *p2 = (flightRec *)b;
if (p1->DestAirportCode < p2->DestAirportCode)
return -1;
else if (p1->DestAirportCode > p2->DestAirportCode)
return +1;
else
return 0;
}
int codeInst(int count, int i, char currCode, char nextCode, flightRec flightInfo[1000]) { // function that counts how many instances of each code exist
count = 0; // set count to zero
i = 0;
currCode = flightInfo[i].DestAirportCode; // get a code from the array, call it currCode
while (i < 1000 ) { // while you've not come to the end of the array
nextCode = (&flightInfo[i+1].DestAirportCode); // get the next code from the array
if (nextCode == currCode) { // if the next code equals the current code
count += 1; // then add one to count
}
else {
printf("Destination Airport Code: %s Count: %i", flightInfo->DestAirportCode, count); // else output code and count
currCode = nextCode; // set currCode to nextCode
count = 0; // set count to 0
}
++i;
}
}
int main(){
flightRec flightInfo[1000];
int i = 0;
int codeInst;
FILE* inFile = NULL;
inFile = fopen("acars.bin", "rb");
struct tm* timestamp;
if (inFile == NULL) {
printf("Could not open file acars.bin.\n");
return -1;
}
while (!feof(inFile)) {
for (i = 0; i < 1000; ++i) {
fread(&flightInfo[i], sizeof(flightInfo), 1, inFile); // read the acars.bin file into an array of these structs
}
for (i = 0; i < 1000; ++i) {
qsort(flightInfo, 1000, sizeof flightInfo, flightCmp); // sort the array
}
for (i = 0; i < 1000; ++i) {
localtime(flightInfo[i].timestamp); // Do localtime () on the timestamp member of the struct, then asctime on the time struct you get back from localtime
return timestamp;
}
int codeInst(flightInfo); // algorithm to count how many instances of each code exists
for (i = 0; i < 1000; ++i) {
printf("Flight Number: %s \nOriginal Airport: %s \nDestination Airport: %s \nDestination Airport Count:%i \nTime: %d \n\n", &flightInfo[i].FlightNum, &flightInfo[i].OriginAirportCode, &flightInfo[i].DestAirportCode, codeInst, timestamp); // print the flightRec structs in form of member columns
}
}
fclose(inFile);
system("pause");
}
Build Messages:
||=== Build: Debug in Project6 (compiler: GNU GCC Compiler) ===|
In function 'codeInst':|
|28|warning: assignment makes integer from pointer without a cast [enabled by default]|
|30|warning: assignment makes integer from pointer without a cast [enabled by default]|
||In function 'main':|
|70|warning: passing argument 1 of 'localtime' makes pointer from integer without a cast [enabled by default]|
|121|note: expected 'const time_t *' but argument is of type 'int'|
|71|warning: return makes integer from pointer without a cast [enabled by default]|
|74|error: expected declaration specifiers or '...' before 'flightInfo'|
|76|warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[7]' [-Wformat]|
|76|warning: format '%s' expects argument of type 'char *', but argument 3 has type 'char (*)[5]' [-Wformat]|
|76|warning: format '%s' expects argument of type 'char *', but argument 4 has type 'char (*)[5]' [-Wformat]|
|76|warning: format '%d' expects argument of type 'int', but argument 6 has type 'struct tm *' [-Wformat]|
83|warning: control reaches end of non-void function [-Wreturn-type]|
c||In function 'codeInst':|
|43|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 10 warning(s) (0 minute(s), 0 second(s)) ===|
You have initially a function called codeInst, after that, in your main function, you declared a integer variable called codeInst, in line 73 you coded a statement that I really don't know what you want to do (int codeInst(flightInfo);).I assume that you want to call the function int codeInst and for that you must:
change the name of the variable like codeInstVarible
assign to codeInstVarible the function codeInstVarible = codeInst()
and fill all existing parameters in the function in case: (int count, int i, char currCode, char nextCode, flightRec flightInfo[1000])
Check out for info:
[c function localtime()][1]
For the error: |121|note: expected 'const time_t *' but argument is of type 'int'|
In your localtime(flightInfo[i].timestamp),
flightInfo[i].timestamp is an int, not a const time_t *(a pointer to a time_t).
For your int codeInst(flightInfo); function, it should have a return type.
In your main function, you wrote
int codeInst(flightInfo);
Which is incorrect. Look at BarbarianSpock's response.

not sure what's going on in this code

I have some C code, and I'm not quite sure what's going on.
#include <stdio.h>
#include <stdlib.h>
#define DIM1 7
#define DIM2 5
#define RES_SIZE 1000
typedef double stackElementT;
typedef struct {
stackElementT *contents;
int maxSize;
int top;
int min2;
} stackT;
void StackInit(stackT *stackP, int maxSize) {
stackElementT *newContents;
newContents = (stackElementT *)malloc(sizeof(stackElementT)*maxSize);
if (newContents == NULL) {
fprintf(stderr, "Not enough memory.\n");
exit(1);
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1;
}
void StackDestroy(stackT *stackP) {
free(stackP->contents);
stackP->contents = NULL;
stackP->maxSize = 0;
stackP->top = -1;
}
int StackIsEmpty(stackT *stackP) { return stackP->top < 0; }
int StackIsFull(stackT *stackP) { return stackP->top >= stackP->maxSize-1; }
void StackPush(stackT *stackP, stackElementT element) {
if(StackIsFull(stackP)) {
fprintf(stderr, "Can't push element: stack is full.\n");
exit(1);
}
stackP->contents[++stackP->top] = element;
}
stackElementT StackPop(stackT *stackP) {
if(StackIsEmpty(stackP)) {
fprintf(stderr, "Can't pop element: stack is empty.\n");
exit(1);
}
return stackP->contents[stackP->top--];
}
int shell(char* s1, int arg) {
printf("> ");
scanf("%s %d%*c", &s1, &arg);
return arg;
}
int main() {
char cmds[DIM1][DIM2] = {{"push"}, {"pop"}, {"add"}, {"ifeq"}, {"jump"}, {"print"}, {"dup"}};
char* s1; int arg;
arg = shell(s1, arg);
printf("%s\n", &s1);
}
Input: push 4. It prints J+ instead of "push" but prints 4 normally.
It also gives these warnings on compile:
stack.c: In function ‘shell’:
stack.c:60: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’
stack.c: In function ‘main’:
stack.c:71: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’
stack.c:65: warning: unused variable ‘cmds’
stack.c:69: warning: ‘arg’ is used uninitialized in this function
Can someone please explain?
When you use the %s format specifier, it expect a value which is a pointer to the start of a string. In C, this type is char *.
Taking your main function, your variable s1 is of type char *. Therefore, s1 is a valid parameter to printf, so this line is valid:
printf("%s\n", s1);
Note the absence of an & in front of s1. In your code, you used the &, which takes the address of s1, the result of which will be of type char **. This is the wrong type, so don't use the &.
The thing is, printf can't actually tell what type its arguments are, since it is a variadic function. It simply uses whatever arguments are there, according to the types specified in the format string.
The same thing goes for scanf, but there is a pitfall: you must make sure that enough memory is allocated to account for the user input, else you will experience a buffer overflow with unpredictable results. Aside from this, printf and scanf are perfectly complementary.
Anyhoo, this takes care of the compiler warnings, aside from the unused cmds variable (it's unnecessary in the provided code). Also, there is the part of args - it really should be a variable declared inside of shell, and not passed as a parameter, since its value is not even used inside shell.
Don't know what's up with the rest of the code. It's superfluous considering your main function only calls on shell.

C code works on Windows (compiled with Visual Studio) but won't compile on Linux (using gcc)

I am currently trying to make a very simple C program for school that creates an array of m integer n (both of which are defined by user input) and either returns the location of the starts of the array or an error message if the array could not be created. It works perfectly well when compiled using Visual Studio, but when I tried to compile it using gcc it throws me a heap of error messages and I simply have no idea what is causing them.
Source code:
#include <stdio.h>
int *create_array(int n, int initial_value);
int main(){
int *arr;
int num;
int numOfNum;
printf("Store this integer:\n");
scanf("%d", &num);
printf("Store the integer this amount of time:\n");
scanf("%d", &numOfNum);
arr = create_array(num, 1);
if(arr == NULL) printf("ERROR");
else printf("Array stored in this location: %p", arr);
return 0;
}
int *create_array(int n, int initial_value){
int *pointer;
int i;
pointer = (int *) malloc(sizeof(int) * 10);
for(i = 0; i < n; i++){
int *p;
p = pointer;
p += n*(sizeof(int));
*p = initial_value;
}
return pointer;
}
Error from gcc:
q1.c: In function âmainâ:
q1.c:18: error: missing terminating " character
q1.c:19: error: ânotâ undeclared (first use in this function)
q1.c:19: error: (Each undeclared identifier is reported only once
q1.c:19: error: for each function it appears in.)
q1.c:19: error: expected â)â before âbeâ
q1.c:19: error: missing terminating " character
q1.c:20: error: missing terminating " character
q1.c:21: error: missing terminating " character
q1.c:39: error: expected declaration or statement at end of input
Seeing the weird characters "ânotâ" I suspect that you are using a bad file encoding. Try copy pasting the code into a linux file editor and save it from that editor into a new file. Try compiling that.
Your code, exactly as you posted it, generates these messages with my gcc
6398652.c:4:5: error: function declaration isn’t a prototype [-Werror=strict-prototypes]
6398652.c: In function ‘main’:
6398652.c:4:5: error: old-style function definition [-Werror=old-style-definition]
6398652.c:18:3: error: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int *’ [-Werror=format]
6398652.c: In function ‘create_array’:
6398652.c:25:3: error: implicit declaration of function ‘malloc’ [-Werror=implicit-function-declaration]
6398652.c:25:21: error: incompatible implicit declaration of built-in function ‘malloc’ [-Werror]
cc1: all warnings being treated as errors
This changed version compiles cleanly
#include <stdio.h>
#include <stdlib.h>
int *create_array(int n, int initial_value);
int main(void) {
int *arr;
int num;
int numOfNum;
printf("Store this integer:\n");
scanf("%d", &num);
printf("Store the integer this amount of time:\n");
scanf("%d", &numOfNum);
arr = create_array(num, 1);
if (arr == NULL) {
printf("ERROR\n");
} else {
printf("Array stored in this location: %p\n", (void*)arr);
}
return 0;
}
int *create_array(int n, int initial_value) {
int *pointer;
int i;
pointer = malloc(10 * sizeof *pointer);
for (i = 0; i < n; i++) {
int *p;
p = pointer;
p += n*(sizeof *p);
*p = initial_value;
}
return pointer;
}

Resources