#include <stdio.h>
#include <stdlib.h>
struct student{
char initials[2];
int score;
};
void sort(struct student* students, int n){
/*Sort the n students based on their initials*/
int i, j, replace;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(students[j] > students[j+1])
{
replace = students[j];
students[j] = students[j+1];
students[j+1] = replace;
}
}
}
}
int main(){
/*Declare an integer n and assign it a value.*/
int n=10;
/*Allocate memory for n students using malloc.*/
struct student* students = (struct student *)malloc(n*sizeof(struct student));
/*Generate random IDs and scores for the n students, using rand().*/
int i;
for(i=0; i<10; i++){
(students + i)->initials[1] = rand( ) % 26 + 'A';
(students + i)->initials[2] = rand( ) % 26 + 'A';
}
/*Print the contents of the array of n students.*/
for(i=0; i<10; i++){
printf("%c%c\n", students[i].initials[1], students[i].initials[2]);
}
/*Pass this array along with n to the sort() function*/
sort(students, n);
/*Print the contents of the array of n students.*/
return 0;
}
I get the following errors when i compile this code,
Program5.c: In function ‘sort’:
Program5.c:23:23: error: invalid operands to binary > (have ‘struct student’ and ‘struct student’)
if(students[j] > students[j+1])
^
Program5.c:25:17: error: invalid operands to binary == (have ‘int’ and ‘struct student’)
replace == students[j];
^
Program5.c:27:23: error: incompatible types when assigning to type ‘struct student’ from type ‘int’
students[j+1] = replace;
Any help would be highly appreciated :)
The first two errors mean that the compiler can't find a > (greater than) operator or a == (equal to) operator that compares a student to a student. The compiler can't just make one up. You need to write your own > and == operators.
The third error means the compiler can't find an assignment operator (=) that takes a student and assigns it to an int. Again, you need to write that operator, because the compiler doesn't know what you want to happen.
You should be able to find the proper syntax for defining these operators by searching for something along the lines of "define c++ == operator" or "define c++ assignment operator".
Remember that arrays in C/C++ are zero-based, and that you're over-writing memory in the initials generation code.
Also watch your array indices in the inner sorting loop; at some point j+1 will be equal to n, and you'll accessing storage that doesn't belong to you.
Your get your first error because the compiler doesn't know how to compare your student structs, it can't tell how to sort them. You must define the operator for this. For example, if you want to order them by score, you can change your student struct to:
struct student {
char initials[2];
int score;
friend bool operator > (const student& lhs, const student& rhs) {
return lhs.score > rhs.score;
}
};
The other two error are caused because you are trying to assign a student struct to an int (students[j] to replace), and vice-versa. Changing the type of replaceto student should fix this problem.
You need to define the following function:
/** #return 0 - if the students are the same
value greater than 0 - if the first student compares greater than the second
value less than 0 - if the second student compares greater than the first
*/
int cmp_student(const struct student* std1, const struct student* std2);
Then in your sort function you can use this function like so:
void sort(struct student* students, int n){
/*Sort the n students based on their initials*/
int i, j, replace;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(cmp_student(&students[j], &students[j+1]) < 0)
{
...
}
}
}
}
Note that there is a problem with the second nested loop in that function. What happens when j == (n - 1), what would the value of j + 1 be?
I would also recommend writing a swap function which takes two index positions and the array and swaps the contents of the array at those two positions. Something like this:
void swap(int id1, int id2, struct student* students);
Related
basically I have 2d array in a struct that I access through a pointer and i can't figure out how to access matrix[i][j] in my if statement
struct Matrix{
unsigned int matrix_size;
int matrix [MAX_MATRIX][MAX_MATRIX];
};
short is_matrix_ok(const struct Matrix*n){
for(int i=0;i<n-matrix_size;i++){
for(int j=0;j<n->matrix_size;j++){
if(n->(matrix+i)[j] ?????)
}
}
Thanks for your answer
Use n->matrix[i][j].
matrix is a member of the structure. matrix+i is not, so you cannot use n->(matrix+i). You must first get the member of the structure, n->matrix, and then you can apply operations to that, like n->matrix[i], which is equivalent to (n->matrix)[i], and then you can apply the next subscript, n->matrix[i][j].
If you want to access it using pointers rather than subscripts, then it would be n->matrix + i to calculate a pointer to subarray i. Then *(n->matrix + i) is that subarray. As an array, it is automatically converted to a pointer to its first element, so *(n->matrix + i) + j calculates a pointer to element j of subarray i. Finally, *(*(n->matrix + i) + j) is element j of subarray i.
Never use that pointer expression in normal code without good reason. Use the easier-to-read n->matrix[i][j].
Try the code below:
#include <stdio.h>
#define ROWS 3
#define COLS 2
struct Matrix{
int matrix[ROWS][COLS];
};
short read_matrix(struct Matrix *M){
int tmp = -100;
for(int i=0;i<ROWS;i++){
for(int j=0;j<COLS;j++){
scanf("%d\n", &tmp);
M->matrix[i][j] = tmp;
//printf("tmp is %d\n", tmp);
}
}
return(0);
}
short is_matrix_ok(const struct Matrix *M){
for(int i=0;i<ROWS;i++){
for(int j=0;j<COLS;j++){
printf("n[%d][%d] = %d\n",i,j,M->matrix[i][j]);
}
}
return(0);
}
int main(){
struct Matrix Mat;
read_matrix(&Mat);
is_matrix_ok(&Mat);
return(0);
}
If you input 1 to 6, output is as follows:
n[0][0] = 1
n[0][1] = 2
n[1][0] = 3
n[1][1] = 4
n[2][0] = 5
n[2][1] = 6
#include<stdio.h>
void main()//this is the way that we pragram in c
{
int arr[][]={{1,2},{1,2},{1,3}};//in class it wasnt required to initialize both
}
the errors:
Error 1 error C2087: 'arr' : missing subscript
Error 2 error C2078: too many initializers
3 IntelliSense: an array may not have elements of this type
I am a beginner , and i saw in class that the professor did the same thing.
also i asked my instructor and he told me that it should raise this error.
can someone please addres me to where and what is the problem?
You're missing the type; all but the first dimension must be specified; and you're missing commas between the aggregate initializers. Working example:
int main(void) {
int arr[][2] = {{1,2}, {1,2}, {1,3}};
}
When you have such a declaration
int arr[][]={{1,2},{1,2},{1,3}};
then the compiler can determine the number of the elements for the left most dimension. There are three initializers so the left most dimension is equal to 3. However the compiler is unable to determine the number of elements in the right most dimension because all these declarations are valid
int arr[][2]={{1,2},{1,2},{1,3}};
int arr[][20]={{1,2},{1,2},{1,3}};
int arr[][200]={{1,2},{1,2},{1,3}};
So you need explicitly to specify the number of elements in the right most dimension of the array. As I can guess you mean the following array declaration
int arr[][2]={{1,2},{1,2},{1,3}};
that is equivalent to
int arr[3][2]={{1,2},{1,2},{1,3}};
Though the MS VS allows a declaration of main like
void main()
nevertheless according to the C Standard the function main without parameters shall be declared like
int main( void )
even if a rerun statement is absent.
You should add type to your array declaration - for example int arr[][].
If you don't want to specify size of columns and rows you have to do it dynamically. For example this way:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4, i, j, count;
int **arr = (int **)malloc(r * sizeof(int *));
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
// Note that arr[i][j] is same as *(*(arr+i)+j)
count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", arr[i][j]);
/* Code for further processing and free the
dynamically allocated memory */
return 0;
}
I have to write a C program to do the following:
Write a function that takes three arguments: a pointer to the first
element of a range in an array, a pointer to the element following
the end of a range in an array, and an int value. Have the function
set each element of the array to the int value.
My code is not working. Here is what I have so far. Any help is appreciated.
#include <stdio.h>
#include <iostream>
int listNumbers[3]{ 1,2,3 };
void Sorter(int *first, int * last, int *value);
int * first = &listNumbers[0];
int * last = &listNumbers[2];
int value;
int main() {
printf("your list numbers are:\n");
int i;
for (int i = 0; i < 3; ++i) {
printf("%d", listNumbers[i]);
}
printf("\n");
printf("enter an integer:\n");
scanf_s("%d", &value);
Sorter( first, last, &value);
printf("your new list numbers are:\n");
int j;
for (int j = 0; j < 3; ++j) {
printf("%d", listNumbers[j]);
}
printf("\n");
system("PAUSE");
return 0;
}
void Sorter(int *first, int * last, int *value) {
int i=0;
printf("value = %d\n", &value);
*first = value;
while (i <= *last) {
*(first + i) = value;
i++;
}
}
First, work out the different between the 2 pointers.
int count = last - first + 1;
The compiler will automatically divide by the size of an integer. We add 1 to make the range inclusive. Now just iterate through each element:
for (int i = 0; i < count; i++) {
first[i] = value;
}
Also, why are you passing the value as a pointer? This should just be a value.
void Sorter(int *first, int *last, int value) {
And when you call it...
Sorter(first, last, value);
Your Sorter function does not satisfy the problem criteria. The parameters are supposed to be two pointers into an array, and an int. Your function instead accepts three pointers.
You could nevertheless have made it implement at least the apparent spirit of the exercise, by using the value to which the third argument points as the fill value, but you don't do that. Instead you assign the pointer itself to each array element. That ought to at least elicit a warning from your compiler, and you ought not to be ignoring its warnings, especially when your code it not doing what you think it should.
Furthermore, the last pointer is expected to point to just past the last element to set, but you use it as if it points to an integer offset from the start pointer. This is almost the opposite of the previous problem: here, you need to use the pointer value itself, not the int to which it points.
So I'm brand new to C and playing around with memory allocation for arrays. I'm trying to create a program that will dynamically allocate space using malloc to reverse an array of floating point numbers.
#include <stdio.h>
#include <stdlib.h>
struct Rec {
float * x;
int size;
};
int main(){
struct Rec a[50];
int i, y;
printf("Enter the number of floating point numbers: ");
scanf("%d", &y);
x = malloc(y * sizeof(struct));
printf("Enter 5 floating point numbers: \n");
for(i = 0; i < sizeof(struct); i++){
scanf("%.3f", &x[i]);
}
printf("The numbers in reverse order are: \n");
for(i = --sizeof(struct); i >= 0; i--){
printf("%f \n", a[i]);
}
}
During compilation, the following errors are generated:
error: use of undeclared identifier 'x'
*x = malloc(y * sizeof(struct);
^
test.c:14:25: error: declaration of anonymous struct must be
a definition
*x = malloc(y * sizeof(struct);
^
test.c:14:32: error: type name requires a specifier or qualifier
*x = malloc(y * sizeof(struct);
^
test.c:14:31: error: type name requires a specifier or qualifier
x = malloc(y * sizeof(struct));
^
test.c:14:24: note: to match this '('
*x = malloc(y * sizeof(struct);
^
test.c:25:3: error: expected '}'
}
^
test.c:9:11: note: to match this '{'
int main(){
^
Your pointer x is part of the structure which is stored in an array. You probably want to access your "x" through the structure. So instead of
x = malloc(y * sizeof(struct));
You probalby want
a[some index].x = malloc(y * sizeof(struct));
This above line will compile but will most likely give you incorrect results. Since you want to allocate it, you want it to be the size of the variable that you are planning to store there, not the size of the struct.
I should mention that there are other problems. You can't iterate through a structure that way. You want to instead iterate over the length of the array (of structs) instead.
There are a lot of issues with your code. I would advise you to practice more with C basics before attempting to do this. Here is approximation of what you might have wanted to achieve with your code:
#include <stdio.h>
#include <string.h>
// This structure can hold array of floats - and their size
struct Rec
{
float * x;
int size;
};
int main()
{
// Declare variable of type rec
struct Rec a;
int i, y;
// How many floats to store? This could also be stored in a.size instead of y
printf("Enter the number of floating point numbers: ");
scanf("%d", &y);
// Create and populate dynamic array
a.x = malloc(y * sizeof(float));
printf("Enter floating point numbers: \n");
for(i = 0; i < y; i++)
{
scanf("%.3f", &a.x[i]);
}
// Print
printf("The numbers in reverse order are: \n");
for(i = y-1; i >= 0; i--)
{
printf("%f \n", a.x[i]);
}
free(a.x);
return 0;
}
I've defined a local structure called item. I'm attempting to sort the items in terms of one of the elements, "uprice". When I attempt to switch the elements in the two items after a hit in the sort, I get an odd error saying that my array a[] of struct item pointers does not actually contain struct items. Here is what I have for code and the error following it:
This is the first portion of the code where I define the bsort function and my struct:
void bsort(struct item* a[], int n);
struct item{
int bcode;
int pcode;
float length;
float width;
int sheets;
int scode;
float price;
float uprice;
};
struct item* list;
This is the second portion of the code where I implement my bsort function:
void bsort(struct item* a[], int n)
{
int i, j, temp;
for (i = 0 ; i < n-1; i++)
{
for (j = 0 ; j < n-i-1; j++)
{
if (a[j].uprice > a[j+1].uprice)
{
temp = a[j].bcode;
a[j] = a[j+1].bcode;
a[j+1].bcode = temp;
//Switch each property of the array individually
}
}
}
}
The error message referring to the code within bsort:
price2.c: In function ‘bsort’:
price2.c:54: error: request for member ‘bcode’ in something not a structure or union
price2.c:55: error: request for member ‘bcode’ in something not a structure or union
price2.c:56: error: request for member ‘bcode’ in something not a structure or union
etc...
The way you have it declared, a is an array of pointers to items. That being the case, you'd need to dereference each a[i] properly:
if (a[j]->uprice > a[j+1]->uprice)
{
temp = a[j]->bcode;
a[j] = a[j+1]->bcode;
a[j+1]->bcode = temp;
//Switch each property of the array individually
}
a[j].uprice
It's still a pointer.