complete sample code is written for you as below:
程序代码:
#include <stdio.h>
#include <string.h>
/**
you are storing a char-pointer in the struct,
so memory for name should be allocated outside
the struct.
*/
typedef struct caption
{
int length;
char *name;
};
int main(int argc, char** argv)
{
struct caption c[3];
char names[3][128] =
{
"John Doe",
"Jane M. Lequi",
"Peter T. Campbell"
};
FILE* fp;
const char* fname = "a.txt";
int i;
c[0].length = 1;
c[0].name = names[0];
c[1].length = 2;
c[1].name = names[1];
c[2].length = 3;
c[2].name = names[2];
fp = fopen(fname, "w");
if(!fp)
{
// do something
}
for(i=0; i<3; ++i)
{
fprintf(fp, "%d %s\n", c[i].length, c[i].name);
}
fclose(fp);
// check a.txt if you got the expected answer
return 0;
}