0

Please some one help me with this..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct{
    int id;
    char nama[50];
} test_t;

void test(int* count, test_t* t){
    (*count) = 5;
    t = (test_t*)malloc(sizeof(*t)*5);
    for(int i=0;i<5;i++){
        t[i].id = i;
        strcpy(t[i].nama, "test");
        printf("id: %i\nnama: %s\n", t[i].id, t[i].nama);
    }


 printf("t size: %lu\n", sizeof(t));
}

int main(int argc, char** argv){
    int a = 1;
    test_t* item;
    test(&a, item);
    for(int i=0;i<a;i++){
        printf("id: %i\nnama: %s\n", item[i].id, item[i].nama);
    }
    return 0;
}

i try to pass pointer to a struct and then make array from it then return the array to calling function.. but i cant get result from that.. any help would be appreciated.. thank you...

btw.. this is the output result

id: 0
nama: test
id: 1
nama: test
id: 2
nama: test
id: 3
nama: test
id: 4
nama: test
t size: 8
id: 1
nama: 
id: -767851619
nama: �
id: -767851396
nama: �
id: -767849773
nama: �
id: -767849398
nama: �
  • Parameters pass values to functions. They do not pass anything back. To pass a value back to the caller, you must either return it as the return value of the function or put it in a place the caller can see. (An example would be a place pointed to by a parameter, but that is not needed here.) – Eric Postpischil Jul 26 '18 at 14:41
  • 1
    parameters are passed by value, thus if you assign something to `t` in `test()` the calling function won't see that. Why not simply return `t`? – Ingo Leonhardt Jul 26 '18 at 14:41
  • This is a common problem; it is a duplicate of numerous questions. The difficulty is finding one which is a good reference duplicate. – Jonathan Leffler Jul 26 '18 at 14:42
  • You are writing code without understanding. You conflict yourself. see `test(&a, item)`. fot the first case, you passed the address of the variable to be modified, why not the second case? – Sourav Ghosh Jul 26 '18 at 14:44
  • Thank you very much for the help... – Agus Budianto Jul 26 '18 at 15:54

0 Answers0