C Programming : Parameter : Can't convert to int* - c

i am new here and i have a question.
I'm doing my C Programming Assignment about Procedure and Struct.
So i want to declare an Array of a Struct, and after that put it as an alias. Here is the code :
typedef struct Mahasiswa
{
int NIM;
char NamaMhs[16];
char KodeMK[6];
char Nilai;
}TabMhs[100];
TabMhs M; //Alias
And i want to use this struct as a parameter of another procedure :
This is the procedure :
void SortDataMhs(struct Mahasiswa M[Nmaks],int n);
and this is the procedure call :
SortDataMhs(&M,n);
But i got an error :
[Error] Cannot convert 'Mahasiswa()][100]' to 'Mahasiswa' for argument '1' 'void SortDataMhs(Mahasiswa*,int)'
Any help? And sorry for asking such a newbie question. Because i am new to Programming :)

This declaration of an array of structure, i.e.:
typedef struct Mahasiswa
{
int NIM;
char NamaMhs[16];
char KodeMK[6];
char Nilai;
}TabMhs[100];
TabMhs M; //Alias
is not good practice. You can read more about it here.
Now, the code below is more readable and understandable:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Mahasiswa
{
int NIM;
char NamaMhs[16];
char KodeMK[6];
char Nilai;
}TabMhs;
TabMhs m[100];
void ss(TabMhs* m, int n){ // `m` is the pointer to array of structures and `n` is the number of elements in that array.
for(int i=0; i<n ; i++){
printf("%d\t%s\t%s\t%c\t%d\n", m[i].NIM, m[i].NamaMhs, m[i].KodeMK, m[i].Nilai, n);
}
}
int main(){
m[0].NIM = 0;
strcpy(m[0].NamaMhs, "m0nama");
strcpy(m[0].KodeMK, "m0kod");
m[0].Nilai='a';
m[1].NIM = 1;
strcpy(m[1].NamaMhs, "m1nama");
strcpy(m[1].KodeMK, "m1kod");
m[1].Nilai='b';
ss(m,2);
return 0;
}
But say tomorrow your array of structures need more (or less) than 100 elements, in that case, you can make that array dynamic by removing the statement TabMhs m[100] and replacing it with this:
int main(){
int n = 10;
TabMhs* m = malloc(sizeof(TabMhs) * n);
/* rest of the code remains same */
free(m);
}

Related

What does "request for member in something not a structure or union" mean?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int busqueda_indexada(int a[], int n, int x) {
int elementos[3]; int indice[3];
int g; int i;
int set=0; int ind=0;
for (i=0; i<n-1; i+=3) {
elementos[ind].nombre=a[i]);
elementos[ind].indice = i;
i+=3;
ind++;
}
if (x<elementos[0].boleto) {
return -1;
} else {
for (i=1; i<g-1; i++)
if (x<elementos[i].elem) {
int ini = elementos[i-1].indice;
int fin = elementos[i].indice;
set = 1;
break;
}
}
if (set==0) {
int ini = elementos[G-1].indice;
int fin = n-1;
}
}
struct elementos {
int indice;
char nombre[100];
int boleto;
} elementos a[3];
int main(int argc, char *argv[]) {
struct elementos a[3] = {"marco", 1, "sin asignar", 2, "pedro", 3};
printf("%s y %d", a[2].nombre, a[2].boleto);
busqueda_indexada(a, n, x)
return 0;
}
I don't know how the indexed search can read my structure. I tried everything and always shows
[Error] request for member '' in something not a structure or union
every time I tried to call a structure. Maybe I defined bad my struct or I call it in the wrong way?
With elementos[ind].nombre You try to access a field on elementos[ind], but that itself is a int. .something in only allowed, if elementos[ind] would eithet be a struct or an union.
You use elementos for two different things:
In busqueda_indexada() for a local array of int;
Outside any function for a structure.
The error (among a lot more) is given the first time for elementos[ind].nombre. This is the indth element of the local array, an int, which is clearly no structure.
Please raise the warning level of your compiler to the maximum and correct your code until all errors and warnings are gone.
Use descriptive names for structures and variables.

Automatic generation of struct printing function in C

I have many programs where structs are defined. And each time, I have to create a function to print the members. For example,
typedef struct {
char name[128];
char address[1024];
int zip;
} myStruct;
void printMyStruct(myStruct myPeople) {
printf("%s\n",myPeople.name);
printf("%s\n",myPeople.address);
printf("%d\n",myPeople.zip);
}
int main()
{
myStruct myPeople={"myName" , "10 myStreet", 11111};
printMyStruct(myPeople);
}
I know that reflection is not supported in C. And so, I write these printing functions for each struct I defined.
But, I wonder if it exists any tricks to generate automatically these printing functions. I would understand that I have to modify a little bit these functions. But, if a part of the job is done automatically, it would be great.
(This example is simple, sometimes struct are nested or I have array of structs or some fields are pointers, ...)
You can of-course print structs, but expect a lot of non-readable output:
#include <stdio.h>
#include <ctype.h>
struct example {
int x;
int y;
char c;
};
#define NOT_PRINTABLE "Not Printable"
void print_structure(const char *structure, size_t size) {
for (size_t i = 0; i < size; i++) {
printf("%ld)\t%.2X: %.*s\n", i, structure[i],
(isprint(structure[i]) ? 1 : sizeof(NOT_PRINTABLE) - 1),
(isprint(structure[i]) ? &structure[i] : NOT_PRINTABLE));
}
}
int main(int argc, char **argv) {
struct example a;
a.x = 5;
a.y = 6;
a.c = 'A';
print_structure((char *)&a, sizeof(struct example));
return 0;
}
But the issue is that, it will print the structs as it is represented in memory. So 4 byte (32 bit) integer 1 will be represented with 4 bytes, not the char '1'.
And due to the way pointers work, you cannot make out if a member is a pointer or a non-pointer.
Another issue is that structures have padding to help with alignment, and better/efficent use of memory. So you would see a lot of 0x00 in the middle.
Remember that C is a compiled language.
let's consider to use https://copilot.github.com/. it's great.
this is what i have with copilot
typedef struct {
char name[128];
char address[1024];
int zip;
} myStruct;
//print struct myStruct >> auto generate by codepilot after you type a comment `print struct myStruct`
void printStruct(myStruct *s) {
printf("name: %s\n", s->name);
printf("address: %s\n", s->address);
printf("zip: %d\n", s->zip);
}

Strange Struct Array Printing Error in C

Hey all I'm having some trouble diagnosing the reason for an error in printing an array of structures in C.
In a separate header file (call it header.h) I have the following typedef'd structure:
typedef struct instruction prog;
struct instruction{
char kind;
char op[4];
};
For my main programing task I want to read from a file a series of what are supposed to be instructions consisting of a type character (the variable kind above) and an instruction consisting of four integers (listed as op above). Examples include R 1004 E 1008, etc. I can read the data in just fine but it seems to be storing things improperly. I wrote the following test code to see if I could find the error but I was still getting the same issue. My goal is to store these as an array of instructions where, using the parlance of the code below, mem[i].kind = 'R' and mem[i].op =1004`.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#include "header.h"
void memFill(prog *P, int x);
void memPrint(prog *P, int x);
int main(){
prog mem[10];
memFill(&mem[0], 10);
memPrint(&mem[0], 10);
return 0;
}
void memFill(prog *P, int x){
char *v = "1004";
for(int i = 0; i< x; i++){
P->kind = 'R';
strcpy(P->op, v);
P++;
}
}
void memPrint(prog *P, int x){
for(int i = 0; i <x; i++){
printf("%c %s\n",P->kind, P->op);
P++;
}
}
This is giving me output that looks like this:
R 1004R1004R1004R1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004R1004
R 1004R1004R1004R1004R1004
R 1004R1004R1004R1004
R 1004R1004R1004
R 1004R1004
R 1004
The reason this is weird is that identical pointer arithmetic has given just fine results with a similar structure. What's going on here? What am I missing?
Buffer overflow on char op[4], then Undefined_behavior
To be able to store "1004" it have to be 5 bytes long to have space for NULL terminator.
struct instruction{
char kind;
char op[5];
};
Literal string "1004" is '1', '0', '0', '4', '\0'
You forgot to give space for the string ending null.
Fix your struct declaration to this:
struct instruction{
char kind;
char op[5];
};
And it will work.
You can also simplify declaration this way:
typedef struct instruction{
char kind;
char op[5];
} prog;

Typedef struct errors when attempting to initialize member(s)

I know the code below is not complete. I'm debugging it as I go and no matter what I do, I can't figure out why I get error: request for member 'gpa' in something not a structure or union (line 22). I'm positive there is more to be done with the code and that there are more warnings and errors, I'm not worried about those yet. Just this one I have never encountered before.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define MAXNAME 11
#define MAXSTUDENTS 9
typedef struct student
{
char name[ MAXNAME ];
double gpa;
char grade;
}student_t;
void grade_students(student_t *, int n);
void print_students(student_t *, int n);
int main()
{
student_t students[ MAXSTUDENTS ];
int n;
students.gpa = n;
FILE *infilep;
infilep = fopen("lab09.in", "r");
}
What I am trying to do is use the typedef members but when I try to follow the format used in my text and classnotes, I get the error.
Variable students is declared as an array of elements of type student_t
student_t students[ MAXSTUDENTS ];
So to access an element of the array you should use the subscript operator as for example
students[0].gpa = 0.0;
Another example can be used in function print_students. Though in the function it is just a pointer nevertheless you can use the same syntax with the subscript operator
void print_students( const student_t *students, int n )
{
for ( int i = 0; i < n; i++ )
{
puts( students[i].name );
//...
}
}

creating, passing, getting back Array of a Struct and loop throuh it in C

I need to execute a function that returns array of a specified struct with variable length. Then I should loop through the returned array.
example struct :
typedef struct student {
int id;
char *name;
int grade;
} Student;
function prototypes 1 :
Student *students;
students = findStudentByGrade(int grade);
function prototypes 2 :
Student *students;
int retval = findStudentByGrade(&students, int grade);
I am bit confused on above methods. How can correctly define a array of struct? call function ? and loop through it untill end? Can some one help me please.
You can do this in this way. This code is working. I tested in CodeLite.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student {
int id;
char *name;
} Student;
Student *findStudent(int *asize, const int grade);
int main(void)
{
Student *stds;
int asize = 0;
stds = findStudent(&asize, 5);
int i;
for (i = 0; i < asize; i++) {
printf("ID : %i\n", stds[i].id);
}
return 0;
}
Student *findStudent(int *asize, const int grade)
{
struct student *stds = malloc(sizeof(struct student) * 3);
stds[0].id = 10;
stds[1].id = 20;
stds[2].id = 40;
*asize = 3;
return stds;
}
Get the array of struc as returned statement and pass an int variable with argument list to get the size back and simply loop through using a for loop. Or else you will find problem in looping. It is more easy to get the array size from the function which create the array.
I mean this is quite a basic question, but:
Defining array of your structures would look like:
int size = ...;
Student *students = (Student*) malloc(sizeof(Student) * size);
Then just pass that to the function (both size and the array) and then just loop until i < size.
Ofcourse, don't forget to:
free(students);
at the end.

Resources