Quote:
Originally Posted by dmjpro
Welcome to TSDN.
You would be better to post the whole Code.
Anyway, have a look at the code given below.
-
struct A
-
{
-
int a,b,c;
-
}; //Structure Declaration.
-
A a;
-
//now to access the member variable use a.a or a.b or a.c.
-
A *a=(A*)malloc(sizeof(A));
-
//now to access the member variable a->a or a->b or a->c.
-
Kind regards,
Dmjpro.
Greetings:
I'm trying to get a handle on passing an array of pointers to structures between functions.
The following code compiles w/out errors and gives a result.
Notice that I didn't use dynamic memory storage (heap), but using the Stack.
I believe that is the correct assumption.
-
#include <stdio.h>
-
-
void *myFunction(unsigned i);
-
typedef struct {
-
char* name; /* '\0'-terminated C string */
-
int number;
-
} SomeSeq;
-
-
int main (int argc, const char * argv[]) {
-
// insert code here...
-
printf("Hello, World!\n");
-
printf("1) myFunction says: %s\n",myFunction(1));
-
printf("2) myFunction says: %i\n",myFunction(2));
-
SomeSeq *myStructure = myFunction(3);
-
printf("3) myFunction says: %s and %i.\n",myStructure->name,myStructure->number);
-
printf("Done.\n");
-
return 0;
-
}
-
-
void *myFunction(unsigned i) {
-
printf("\n{myFunction}");
-
if (i == 1) {
-
// Character String.
-
return "hello\0";
-
} else if (i == 2) {
-
// Integer.
-
return (int*)555; // Note the int pointer cast of a void pointer.
-
} else {
-
// Structure.
-
SomeSeq *myStruct;
-
myStruct->name = "Frederick C. Lee";
-
myStruct->number = 123;
-
return (SomeSeq *)myStruct;
-
}
-
}
-
The output is:
-
run
-
[Switching to process 662 local thread 0xf03]
-
Running…
-
Hello, World!
-
-
{myFunction}1) myFunction says: hello
-
-
{myFunction}2) myFunction says: 555
-
-
{myFunction}3) myFunction says: Frederick C. Lee and 123.
-
Done.
-
-
Debugger stopped.
-
Program exited with status value:0.
-
...However, I need to use dynamic memory (heap):
-
....
-
} else {
-
// Structure.
-
// SomeSeq *myStruct;
-
SomeSeq *myStruct=(SomeSeq*)malloc(sizeof(SomeSeq)); // Using memory.
-
myStruct->name = "Frederick C. Lee";
-
myStruct->number = 123;
-
return (SomeSeq *)myStruct;
-
}
-
I get the same output.
But this time I'm getting the compiler warning:
- "warning: incompatible implicit declaration of built-in function 'malloc'"
Why? I looks like I'm type-casting okay.
Also, I 'free' the memory in main() after the function call:
-
int main (int argc, const char * argv[]) {
-
// insert code here...
-
printf("Hello, World!\n");
-
printf("1) myFunction says: %s\n",myFunction(1));
-
printf("2) myFunction says: %i\n",myFunction(2));
-
SomeSeq *myStructure = myFunction(3);
-
printf("3) myFunction says: %s and %i.\n",myStructure->name,myStructure->number);
-
free(myStructure); // Freeing Stucture memory <---
-
printf("Done.\n");
-
return 0;
-
}
-
Is this good code? Why am I getting the compiler warning?
Ric.