简体   繁体   中英

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

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, ie:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM