Getting error about "differs in level of indirection" - arrays

Hi I just completed coded my project, but when I trying to compile I kept getting this error. Which is '<=': 'int' differs in levels of indirection from 'int *', i don't know what is happening, and I already check for the pointer and already put it when defining variable type and still cannot compile it safely.
#define _CRT_SECURE_NO_WARNINGS
/* C Program to find Shortest Distances or Path */
#include<stdio.h>
#define WORD 200
int main(void) {
int path, point = 1;
int* ncity[WORD];
char* cityname[WORD][WORD];
float distance[WORD][WORD];
float total[WORD];
printf("This program will input 5 path and calculates the minimum between KL Sentral, KL & Jurong East, Singapore");
printf("\n\t\t-------------------------------------------------------------");
printf("\n\t\tMinimum Path between KL Sentral, KL & Jurong East, Singapore");
printf("\n\t\t-------------------------------------------------------------");
printf("\nPlease enter the total path that you want to calculate: ");
scanf("%d", &path);
for (int i = 1; i <= path; i++) {
printf("\n\n----Path %d----", i);
printf("\nState the number of city that the path cross: ");
scanf("%d", ncity[i]);
for (int x = 1; x <= path; x++) {
for (int y = 1; y <= ncity[i]; y++) {
printf("\nCity %d named : ", y);
scanf("%s", &cityname[x][y]);
printf("\nEnter the distance to the city %d: ", y);
scanf("%f", &distance[x][y]);
total[x] = +distance[x][y];
}
}
}
//Find the minimum path
for (int x = 1; x <= path; x++) {
if (total[x] < total[point]) {
point = x;
}
}
printf("\nThe minimum path between KL Sentral, Kuala Lumpur & Jurong East, Singapore");
printf("\nPath: Path %d", point);
printf("\nTotal Distance: %f", total[point]);
printf("\n\t\tCity Name");
//Loop for 42
for (int z = 1; z <= ncity[point]; z++) {
for (int x = 1; x <= path; x++) {
for (int y = 1; y <= ncity; y++) {
printf("\n\t\t %s", cityname[x][y]);
printf("\n\t\t %f km", distance[x][y]);
}
}
}
}
This the error that had been listed once i started compiling my code

By using z <= ncity[point] inside your loop you compare 'z' to the actual number of the address where your ncity[pointer] value is stored. Usually it is a big 'int' value. I can't get why you need an array of pointers here, but to get the first value of the ncity[point] you need to derefence that: *ncity[pointer]. The same happening inside your third loop: y <= ncity. You compare 'y' variable with the number of address of your ncity variable. Again, pretty big number, so most likely 'y' variable will be outside of 'cityname' and 'distance' and then you will get 'segmentation fault' error. To get the whole size of 'ncity' you need to iterate though all values or just use path valiable inside your third loop
for (int y = 1; y <= path; y++) {
printf("\n\t\t %s", cityname[x][y]);
printf("\n\t\t %f km", distance[x][y]);
}

Related

Matrix Multiplication in C - Problem with inputs

I've written a program which carries out matrix multiplication using functions. The function which i presume is wrong is as follows:
void obtainMatrixElems(int mtrx[][10], int row_elems, int col_elems){
printf("Kindly enter matrix elements: \n");
for(int x = 0; x < row_elems; x++){
for(int y = 0; y < col_elems; y++){
printf("Enter element at position %d,%d: \n", x+1, y+1);
scanf("&d", &mtrx[x][y]);
}
}
}
It seems you are missing a "+" at multAns[x][y] = matrix1[x][y] * matrix2[x][y];.
It should rather be:
// Also note the change variables used for referencing cells ...
multAns[x][y] += matrix1[x][z] * matrix2[z][y];
In case your last operation result is 0 then this explains why you get a 0 matrix..
EDIT:
The sign is one of the problems .. There is also something wrong with the way you get input from the user.
for(int x = 0; x < row_elems; x++){
for(int y = 0; y < col_elems; y++){
printf("Enter element at position %d,%d: \n", x+1, y+1);
// Note the change of "&" to "%" and the extra sequence
// "\r\n" which expects the user to press ENTER (i.e.:
// new line) between input cells
rc = scanf("%d\r\n", &mtrx[x][y]);
if (rc != 1) {
printf("ERROR: scanf did not proceed as expected\r\n");
}
}
}
There is an error in your call to scanf
It should read
scanf("%d", &mtrx[x][y]);
Also take care with hitting the Enter Key after each input. To be safe you should catch it. Use something like
scanf(" %d", &mtrx[x][x]);

Can't Print " * " in C

for some reason I am unable to print out "* " in my program. I want to print out * if the condition is met. the condition is if the rainfall that day is greater than the average.
under the mean column, i am getting weird symbols. i tried debugging to decimals and get -112 for ascii. i dont understand but i tried researching!
I am new to C so please be understanding. Just learned like 2 days ago!!.
Here is my code :
//Assignment one 9/20/2018
//Anthony Lomaistro and David Luong
//luongd5#student.lasalle.edu
//lomaistroa1#student.lasalle.edu
#include <stdio.h>
main() {
int n = 0; //counters for the loops
int x = 0; // counter for the loops
int counter = 0; // counter whenever i need to keep track of increments
int days_input = 0; // how many days we are keeping track of
int number_of_days = 0;
double rainfall_input = 0;
double rainfall_amount = 0; // how much rainfall per day
double rainfall_average = 0; // average of rainfall
double rainfall_total = 0;
double rainfall_counter = 0; // count how many days it rained above the average
int correct = 0;
double rainfall_array[50];//array that contains the user input
char rainfall_condition[50]; // array that contains the *
double sum = 0;
double average = 0;
double percent_days = 0; //rainfall % above average
double valid = 0;
double valid2 = 0;
printf("Welcome to Lomaistro and Luong's Rainfall Program \n");
printf("How many days would you like to keep track of? Please enter a value between 1 and 50: #%d:", n + 1);
//printf(number_of_days);
while (valid == 0) {
scanf_s("%d", &number_of_days);
if ((number_of_days > 50) || (number_of_days <= 0)) { // come back to this, this doesnt do anytihng
printf("Invalid value, please enter in a day that is between 1 and 50 \n");
}
else {
valid = 1;
}
}
//getting the user to enter in the rainfall
for (x = 0; x < number_of_days; x = x + 1) {
valid2 = 0;
while (valid2 == 0) {
printf("Enter rainfall (in inches): ");
scanf_s("%lf", &rainfall_amount);
if ((rainfall_amount >= 0) && (rainfall_amount <= 10)) {
valid2 = 1;
rainfall_array[x] = rainfall_amount;
}
else
printf("Please enter in a valid rainfall amount between 1 and 10");
}
}
//computing average
for (n = 0; n < number_of_days; n = n + 1) {
sum += rainfall_array[n];
average = sum / number_of_days;
}
printf("Mean daily rainfall(in inches): %lf", average);
//seeing if the * should be the array or not
for (n = 0; n < number_of_days; n = n + 1) {
if (rainfall_array[n] > average) {
rainfall_condition[n] = "*";
rainfall_counter = rainfall_counter + 1;
}
else
rainfall_condition[n] = "empty";
}
// print out the thing
printf("\n Days \t Amount \t >Mean \n");
printf("==============================\n");
for (n = 0; n < number_of_days; n = n + 1) {
printf("%d \t %f \t %c \n", n + 1, rainfall_array[n], rainfall_condition[n]);
}
percent_days = rainfall_counter / number_of_days;
percent_days = percent_days * 100;
printf("Number of days that rained above average : %f \n", rainfall_counter);
printf("Percentage of days that rained above average: %f%% \n", percent_days);
system("pause");
}
rainfall_condition is an array of char, but you're putting a pointer to a string literal in there when you use "*". Use '*' for a character literal instead. To be more specific, this line:
rainfall_condition[n] = "*";
Should be:
rainfall_condition[n] = '*';
Turn some warnings on in your compiler; the first line (what you have now) isn't valid C code and you should be seeing a diagnostic message to that effect.
Edit: now that I've read more of the code, it appears you want either a * or an empty in that column? In that case you want to change the variable declaration to:
char *rainfall_condition[50]; // array that contains the *
And then change the print statement to:
printf("%d \t %f \t %s \n", n + 1, rainfall_array[n], rainfall_condition[n]);

Extra values when printing an array(converting from %s to %c)

I am trying to create a simple program where the user will have to enter a series of numbers and the program should output the square and the cube of the given number. However, when I try to use an array, it prints some random numbers I didn't even input. Any help would be appreciated to eliminate the unecessary input. Thank you.
#include <stdio.h>
int main()
{
char *value;
value = malloc(sizeof(20));
float answer;
int x;
int y;
scanf("%s" , value);
for(x=0; x < 20; x++)
{
y = value[x] - '0';
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}
You are taking input in char and doing arithmetic operations on it.
Use this code, it will give you correct output.
#include <stdio.h>
int main()
{
int *value;
value = (int *)malloc(20 * sizeof(int));
//float answer;
int x;
int y;
for(x=0; x < 20; x++)
{
scanf("%d" , value + i);
}
for(x=0; x < 20; x++)
{
y = value[x];
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}
The problem is with your malloc statement.
sizeof is used to determine the parameter size - in your case a hard-coded integer. The generated array is of size 4, which is exactly sizeof(20) instead of 20 integers which is 20*sizeof(int). It will be best to allocate the array statically if you know what size you need, see code below:
#include <stdio.h>
int main()
{
// This line sets value to an array of 20 ints
int value[20];
// Another, less favorable option, but still works:
// char *value = malloc(20 * sizeof(int))
float answer;
int x;
int y;
scanf("%s" , value);
for(x=0; x < 20; x++)
{
y = value[x] - '0';
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}
The expression sizeof(20) returns the size of an int (the literal 20 is an int), which is typically only 4 bytes. In other words, you are only allocating a single integer for your array. All access outside of that single integer will result in undefined behavior.
You need to allocate sizeof(int) times the number of elements, if you want to dynamically allocate the memory. Or (which I recommend) use a normal array:
int value[20];
There is also another problem, in that you only read a single value from the user. You should probably be reading in the loop too.
But if you read in the loop, then there is really no need to even have an array to begin with, only a single int Variable which you read into, and then print its value as squared and cubed.
So the code could be simplified as
#include <stdio.h>
int main(void)
{
int value;
for (unsigned i = 0; i < 20 && scanf("%d", &value) == 1; ++i)
{
printf("The square of %d is: %d\n", value, value * value);
printf("The cube of %d is: %d\n", value, value * value * value);
}
return 0;
}
You also need to be careful of overflows when multiplying.

error in output of long number multiplication

I have written a code in c for long number multiplication but output is not being displayed on the IDE. Please can you point out the error in the given code. Also which language is more efficient for solving these type of problems?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10000
void main()
{
char ac[MAX];
char bc[MAX];
int a[MAX],b[MAX];
int mul[MAX];
int c[MAX];
int temp[MAX];
int la,lb;
int i,j,k=0,x=0,y;
long int r=0;
long int sum = 0;
la=strlen(ac)-1;
lb=strlen(bc)-1;
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
for(i=0;i<=la;i++){
a[i] = ac[i] - 48;
}
for(i=0;i<=lb;i++){
b[i] = bc[i] - 48;
}
for(i=lb;i>=0;i--){
r=0;
for(j=la;j>=0;j--){
temp[k++] = (b[i]*a[j] + r)%10;
r = (b[i]*a[j]+r)/10;
}
temp[k++] = r;
x++;
for(y = 0;y<x;y++){
temp[k++] = 0;
}
}
k=0;
r=0;
for(i=0;i<la+lb+2;i++)
{
sum =0;
y=0;
for(j=1;j<=lb+1;j++){
if(i <= la+j){
sum = sum + temp[y+i];
}
y += j + la + 1 ;
}
c[k++] = (sum+r) %10;
r = (sum+r)/10;
}
if (r==1)
{
c[k]=r;
}
j=0;
for(i=k-1;i>=0;i--){
mul[j++]=c[i];
}
for(i=0;i<j;j++)
{
printf("%d",mul[i]);
}
}
You calculate the length of the input strings before assigning the strings:
la=strlen(ac)-1;
lb=strlen(bc)-1;
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
If you instead do it the other way around the program actually does something:
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
la=strlen(ac)-1;
lb=strlen(bc)-1;
Your second problem is in the last part of your code:
for(i=0;i<j;j++)
{
printf("%d",mul[i]);
}
You're incrementing j instead of i, it should be:
for(i=0;i<j;i++)
{
printf("%d",mul[i]);
}
Another little thing, this isn't really clear what it does to the uninitiated:
a[i] = ac[i] - 48;
if you write it like this it's easier to understand:
a[i] = ac[i] - '0';
Use remove those la and l assignment and put it after scanning the strings like below.
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
la=strlen(ac)-1;
lb=strlen(bc)-1;
for(i=0;i<=la;i++){
a[i] = ac[i] - 48;
}
for(i=0;i<=lb;i++){
b[i] = bc[i] - 48;
}
Even in the last part of your code there is an error.Inside the loop you have used for(i=0;i<j;j++) replace it with for(i=0;i<j;i++).
I would also suggest you to change the size of temp array to 2*MAX+2.Because suppose somebody enters a number of 8000 digits then temp wont be able to store these many digits if the size is restricted to MAX only.
you can use java and python languages for doing same. In Java there is separate class known as BigInteger.
Scanner sc=new Scanner(System.in);
BigInteger b1,b2,b3;
String num1,num2;
System.out.println("Enter the first integer");
num1=sc.next();
System.out.println("Enter the second integer");
num2=sc.next();
b1=new BigInteger(num1);
b2=new BigInteger(num2);
b3=b1.multiply(b2);
System.out.println("The product of "+b1+" and "+b2+" is "+b3);

C array with structs

I am a very beginner at structs and barely understand what they are useful for. I have an assignment to create an array with space for 5 points. Every point will be entered by the user.
I don't understand how to use structs with arrays. I tried this but it doesn't work at all...
#include <stdio.h>
int main(void)
{
struct Input
{
int x;
int y;
};
struct Input arr[5];
for(int i=1; i <= 5; i++)
{
printf("Enter coordinates for point #%d (x,y): ", i);
scanf("%d,%d", &arr[i].x, &arr[i].y);
}
printf("\n\nYou entered:\n");
for(int i=1; i <= 5; i++)
{
printf("Point #%d: %d, %d\n", i, arr[i].x, arr[i].y);
}
getchar();
getchar();
return 0;
}
EDIT
I am trying to calculate the average of the x coordinations, but obs.avgX doesn't work like planned, the calculation always gets 0.
#include <stdio.h>
int main(void)
{
struct Observations
{
int x;
int y;
double avgX;
double avgY;
};
struct Observations arr[5];
struct Observations obs;
for(int i=0; i < 5; i++)
{
printf("Enter coordinates for point #%d (x,y): ", i +1);
scanf("%d, %d", &arr[i].x, &arr[i].y);
}
printf("\n\nYou entered:\n");
for(int i=0; i < 5; i++)
{
printf("Point #%d: %d, %d\n", i, arr[i].x, arr[i].y);
}
obs.avgX = arr[0].y + arr[1].y + arr[2].y + arr[3].y + arr[4].y / 5;
printf("Average of X: %d", obs.avgX);
getchar();
getchar();
return 0;
}
If you need to create an array of 5 points, first you have to define what a point is.
For example:
struct Point {
int x;
int y;
};
Then you have to define an array of 5 points:
struct Point array_of_points[5];
And you can use it like this:
array_of_points[0].x = 20;
array_of_points[0].y = 10;
// etc...
array_of_points[4].x = 3;
array_of_points[4].y = 8;
SirDarius gave a nice explanation about code.
You said
barely understand what they are useful for
In fact , you can consider , that structs are a kind of "data saver" where you can store DIFFERENT or MULTIPLE types of data .
For example , using arrays , you can not store both x and y coordinates at a cell (Multiple types of Data).
Moreover , if you want to store a Student's School Info , you may want to store , his unique ID (integer) ,his name (string) , his grade (integer) and the average of each lesson (float) (Different Data). Using structs you can easily store them that way :
struct Student {
int ID;
char * name;
int grade;
float average;
}
Hope that helped to understand ,the reason why structs are really useful :)
Braces are missing as below when computing the average,
obs.avgX = (arr[0].y + arr[1].y + arr[2].y + arr[3].y + arr[4].y) / 5;
Also to print a double type variable you should be using %f as the format specifier rather than %d.

Resources