|
-
October 11th, 2005, 04:39 PM
#1
Passing array of struct as reference
Hi there,
I'm trying to pass a pointer to struct to a function , the function has to process and store data in the array. This is the code, when running the program it crushes. I don't want to return the pointer (like: return MyArrayPtr), I need to point the passed pointer to the new memory address.
Thanks, Eli
#include <stdio.h>
#include <malloc.h>
typedef struct
{
char name[80];
int id;
}MyStruct;
int MyFunc(MyStruct *MyPtr);
void main()
{
int i;
MyStruct *MyPtr = NULL;
MyFunc(MyPtr);
for(i=0;i<100;i++)
{
printf("Name: %s, id: %d\n",MyPtr[i].name, MyPtr[i].id );
}
}
int MyFunc(MyStruct *MyPtr)
{
int i;
MyStruct *MyArrayPtr = (MyStruct*)malloc(sizeof(MyStruct)*100);
for(i=0;i<100;i++)
{
MyPtr[i].id = i;
sprintf(MyPtr[i].name, "Eli-%d", i);
}
MyPtr = MyArrayPtr;
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|