iso c90 forbids mixed declarations and code - c

This is my coding and I am getting the above error in the line where i declared int *intpointer. Please help me in solving this.
#include <stdio.h>
int main()
{
int intarray[5] = {10,20,30,40,50};
int i;
for(i = 0; i < 5; i++)
printf("intarray[%d] has value: %d - and address # %x\n", i, intarray[i], &intarray[i]);
int *intpointer = &intarray[4];
printf("address: %x - has value %d\n", intpointer, *intpointer);
intpointer--;
printf("address: %x - has value %d\n", intpointer, *intpointer);
return 0;
}

Place this declaration
int *intpointer = &intarray[4];
in the beginning of the function code block after the declaration of intarray.
As error message reports you compile your code as C90 code that requires that declarations would be before other statements.

Related

A basic question trying to make a structure

What I'm trying to do is get student's name and score in three subjects in the form of a structure array and print their name and average score.
Where is my mistake?
#include <stdio.h>
typedef struct
{
char name[5];
int Kor; //yeah the three subjects
int Eng;
int Math;
}data;
double avg(int a, int b, int c) //to get the average
{
double m;
m = (a + b + c) / 3;
return m;
}
int main()
{
data group[3];
for (int i = 0; i < 3; i++)
{
scanf("%s %d %d %d", group[i].name, group[i].Kor, group[i].Eng, group[i].Math);
}
for (int j = 0; j < 3; j++)
{
printf("%s %lf\n", group[j].name, avg(group[j].Kor, group[j].Eng, group[j].Math));
}
return 0;
}
One thing you should make sure and do is compile with most/all compiler warning flags on. In your case, when I compiled your program with GCC, using the flags -W -Wall -Wextra, I got the following warnings:
<source>: In function 'main':
<source>:23:20: warning: format '%d' expects argument of type 'int *', but argument 3 has type 'int' [-Wformat=]
23 | scanf("%s %d %d %d", group[i].name, group[i].Kor, group[i].Eng, group[i].Math);
| ~^ ~~~~~~~~~~~~
| | |
| int * int
and the same warning for group[i].Eng and group[i].Math.
These compiler warnings are very often actually errors of yours, which, at runtime, will result in the program crashing or producing garbage. In your case, you need to pass the address of the value you want to read from the input.
This does not mean that's the only issue with your code, but you should really let the compiler help you before asking us for help.
I change the scanf, '&' operator is used to access to the address in the memory location. scanf("%d",&a) means that the value entered from the keyboard must be stored in the memory LOCATION where which is given the name 'a'.
and change the calculating function of the average because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be casted to a double.
#include <stdio.h>
typedef struct
{
char name[5];
int Kor; //yeah the three subjects
int Eng;
int Math;
}data;
double avg(int a, int b, int c) //to get the average
{
double m;
m = (a + b + c) / 3.0;
return m;
}
int main()
{
data group[3];
for (int i = 0; i < 3; i++)
{
printf("enter your name ,Kor grade ,Eng grade ,Math grade\n");
scanf("%s %d %d %d", group[i].name, &group[i].Kor, &group[i].Eng, &group[i].Math);
}
for (int j = 0; j < 3; j++)
{
printf("name:%s avg:%lf\n", group[j].name, avg(group[j].Kor, group[j].Eng, group[j].Math));
}
return 0;
}

Invalid conversion 'void*' to 'struct*' [duplicate]

This question already has answers here:
malloc - invalid conversion from void* to double*
(2 answers)
Closed 4 years ago.
I'm beginner in C. I'm trying to practice with solving some problems. And I'm getting this error when I compile my code.
[Error] invalid conversion from 'void*' to 'triangle*' [-fpermissive]
The code and purpose is explained below.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct triangle
{
int a;
int b;
int c;
};
typedef struct triangle triangle;
//sort_by_area() function is here
int main()
{
int n;
scanf("%d", &n);
triangle *tr = malloc(n * sizeof(triangle));
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
}
sort_by_area(tr, n);
for (int i = 0; i < n; i++) {
printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
}
return 0;
}
As you can see I have structure and I tried to allocate memory for it with the quantity of input. And try to use it for sort_by_area function. But the problem is triangle *tr = malloc(n * sizeof(triangle)); line gives me the error mentioned above.
Also this code is working for online compilers. I tried to run this code on DEV C++ with default settings. I don't know about the versions and changing the versions of my compiler. I don't even know whether it is about the compiler version. But I am wondering why I'm getting this error. What is the logic behind.
This looks like C code, but you're compiling with a C++ compiler. As such, it complains on the line you mentioned because malloc returns a void * but you're assigning the result to a triangle *.
In C++ an explicit cast is required for this. In C, a void * may be implicitly converted to or from any object pointer type.
Since this appears to be C code and not C++ code, you should compile with a C compiler.
You compile this program as C++ program and this implicit conversion is not allowed in C++.
As I know dev C++ uses MinGW and you may use -xc option to compile program as C program or Settings -> language standard -> and choose the language standard needed
The code looks like C code but you are compiling it with C++ compiler.
Make sure that the file has proper extension for C++(not .c extension).
malloc() returns a (void *) pointer by default, so you have to explicitly cast the (void *) to (triangle *) in your code.
But if you are writing C++ code then I would recommend not to use malloc and free, instead try to use "new" operator in C++ since while instantiating objects it will call the constructors as well(unlike in malloc).
So to avoid complications go with new and delete in C++.
The code in C should look like (file a.c)
Compile using: gcc a.c -o a.o
Run using : ./a.o
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct triangle {
int a;
int b;
int c;
};
typedef struct triangle triangle;
int main() {
int n;
scanf("%d", &n);
triangle *tr = (triangle *)malloc(n * sizeof(triangle));
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
}
//sort_by_area(tr, n);
for (int i = 0; i < n; i++) {
printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
}
free(tr);
return 0;
}
The same code in C++ would look like (file a.cpp)
Compile using: g++ a.cpp -o a.o
Run using : ./a.o
#include <iostream>
using namespace std;
struct triangle {
int a;
int b;
int c;
};
int main() {
int n;
cin >> n;
triangle *tr = new triangle[n];
for (int i = 0; i < n; i++) {
cin >> tr[i].a >> tr[i].b >> tr[i].c;
}
// sort_by_area(tr, n);
for (int i = 0; i < n; i++) {
cout << tr[i].a << " " << tr[i].b << " " << tr[i].c << "\n";
}
delete [] tr;
return 0;
}
triangle *tr = (triangle*)malloc(n * sizeof(triangle));
Change the line as shown above. malloc returns generic pointer, so you need to explicitly typecast it to your desired pointer.
Refer this

Function which takes an int pointer * as an argument and returns a struct. Storing data in struct struct* and printing results

I'm running into this problem which I think should not happen:
Here are the errors I'm getting.
Sorry for bad formatting, coding on notepad and cntr c&v to compiler (tend to do this from time to time)
~/workspace/Exam1 $ gcc -g payload.c -o payload
payload.c: In function ‘main’:
payload.c:63:31: warning: initialization from incompatible pointer type [enabled by default]
struct payload* calcVal = getCalc(arr, num);
^
payload.c:65:36: error: dereferencing pointer to incomplete type
printf("OddSum : %d\n", calcVal->sumOdd);
^
payload.c:66:40: error: dereferencing pointer to incomplete type
printf("Even Count : %d\n", calcVal->evenCount);
^
payload.c:67:37: error: dereferencing pointer to incomplete type
printf("Minimum : %d\n", calcVal->min);
^
payload.c:68:37: error: dereferencing pointer to incomplete type
printf("Maximum : %d\n", calcVal->max);
I honestly do not understand what the problem is and why I keep running into this. Am I passing struct wrong?
#include<limits.h> //for min/max
#include <stdio.h>
#include <stdlib.h>
struct payLoad{
int sumOdd;
int evenCount;
int min;
int max;
};
struct payLoad* getCalc(int *arr, int n){
int i = 0;
int min= INT_MAX;
int max = INT_MIN;
int sum = 0;
int even = 0;
struct payLoad* calcVal = malloc(sizeof(struct payLoad)); //watch spelling
for(i=0;i <n;++i){
if(arr[i]%2==0){
++even;
}
if (arr[i] < min){
min = arr[i];
}
}
if (arr[i] > max){
max = arr[i];
}
if(arr[i]%2==1){
sum = sum + arr[i];
}
calcVal->sumOdd = sum;
calcVal->evenCount = even;
calcVal->max = max;
calcVal->min = min;
return calcVal;
}
int main(){
int num;
int i=0;
//int min= INT_MAX:
//int max = INT_MIN:
int sum = 0;
printf("Enter the number of array element: ");
scanf("%d", &num);
int *arr = (int *)malloc(num*sizeof(int));
for(i=0;i <num;++i){
printf("Enter the value: ");
scanf("%d", &arr[i]);
}
struct payload* calcVal = getCalc(arr, num);
printf("OddSum : %d\n", calcVal->sumOdd);
printf("Even Count : %d\n", calcVal->evenCount);
printf("Minimum : %d\n", calcVal->min);
printf("Maximum : %d\n", calcVal->max);
}
Edit: fixed typos and spellings, removed link, cntr c&v errors
Your program is having several typo's, like at several places you have:
struct payload
^
payload should be payLoad.
Here:
if(arr[i]%2==1)
sum = sum + arr[i];
}
You forgot to put {. It should be:
if(arr[i]%2==1) {
sum = sum + arr[i];
}
In main():
int num,
Instead of , it should be ;.
Again in main():
printf("OddSum : %d\n", calcVal->oddSum);
Look at your struct payLoad declaration and you will find that it is having a member sumOdd and not oddSum.
The compiler must be reporting all these as errors. Take a close look at them, try to identify the cause, fix it and build it again.
Whatever memory you are allocating dynamically you should free it. Once the program terminates the memory owned by it will be freed automatically but as a good programming practice, you should explicitly free the memory allocated dynamically once you are done with it.

cast to pointer from integer of different size

I keep getting this warning
c:9:80: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
printf("Char= %c ASCII = %i hex = %x pointer = %p \n", i, i, i , (void*)i );
Code
#include<stdio.h>
int main (void) {
int *i;
for (int i = 75; i < 75 + 26; i++) {
printf("Char= %c ASCII = %i hex = %x pointer = %p \n", i, i, i , (void*)i );
}
return(0);
}
I fail to see what the question might be that is not answered by the compiler warning. You've got a variable "i" of type int (32 bit on 64 bit platforms), shadowing another variable called "i" in the main program.
You're casting the int variable to void*, and the compiler says you can't do that, because you are 32 bit short. Rename one of the two variables called i in your program to resolve.
You’re getting the warning because the variable “i” is declared twice in the same scope. The memory address of ‘i’ in your loop doesn’t change so what do you need the pointer outside the loop for?
#include<stdio.h>
int main (void) {
for (int i = 75; i < 75 + 26; i++) {
printf("Char= %c ASCII = %i hex = %x pointer = %p \n", i, i, i , &i );
}
return(0);
}
or yet still if you still want to have two variables.
#include<stdio.h>
int i;
int *j = &i;
int main (void) {
for ( i = 75; i < 75 + 26; i++) {
printf("Char= %c ASCII = %i hex = %x pointer = %p \n", i, i, i , (void *)j );
}
return(0);
}

"error: expected ';', ',' or ')' before numeric constant" is coming up to my code

The program is about function making an average. I get an error:
error: expected ';', ',' or ') before numeric constant
within the avg_array() function whenever I build it. Help would be appreciated, thanks!
#include <stdio.h>
#define SIZE 5
// Prototypes
int avg_array (int*, int);
main()
{
int values[SIZE];
int avg;
int i;
printf("Enter 5 numbers please. \n");
for(i=0; i<SIZE; i++)
{
scanf("%d", &values[i]);
}
avg = avg_array(values, SIZE);
printf("\n The avg of the array is %d \n", avg);
getchar();
getchar();
} // end main()
/* Implement avg_array() WHERE THE ERROR PERTAINS */
avg_array(int my_array[], int SIZE)
{
int sum;
int i;
int fxn_average;
for(i=0; i<SIZE; i++)
{
sum = sum + my_array[i];
}
fxn_average = (sum/SIZE);
return (fxn_average);
}
You are using the identifier SIZE as an argument. This is also a macro that gets converted to 5 by the preprocessor. After the preprocessor applies the macros, it would look like
avg_array (int my_array[], int 5)
Since 5 is a numeric constant instead of an identifier, it generates an error. Change the variable name.
It looks like you also have a function signature missing a return type, which should match the prototype declared above. Try this instead:
int avg_array (int *my_array, int size)
{
int sum = 0;
int i;
for(i=0; i<size; i++)
{
sum = sum + my_array[i];
}
return sum/size;
}
The variable sum should be initialized to 0. The local variable fxn_average is not needed because you can use just return sum/size; at the end instead.
I changed the type of the first argument from int[] (array of int) to int * (pointer to int) so the function definition matches the prototype given in the question. The function was declared as
int avg_array (int*, int);
These arguments have no identifiers; only their types are specified. This is valid C, but many style guides prescribe against it since naming arguments helps the reader understand meaning or intent. If you are writing a programming interface, for example, all the programmer will likely see is the function prototypes in a header file. It must be clear what the arguments are to write a correct function call. Anyway, adding in identifiers looks like:
int avg_array (int *my_array, int size);
which is the same as in the definition I used above.

Resources