B
brownqued
I have the following code.
#define NUMBER 100
#include <stdlib.h>
struct sData
{ char test[NUMBER];
int length;
};
int main(int argc, char *argv[])
{ int a, b;
int NumberOfRows=4, NumberOfColumns=2;
char ctest[]="test";
struct sData **StructArray=NULL;
int len=strlen(ctest);
printf("%d %d\n", sizeof(*StructArray), sizeof(**StructArray));
StructArray=malloc(sizeof(*StructArray) * NumberOfRows);
if (StructArray==NULL) return 1;
for (a=0; a<NumberOfRows; a++)
{ StructArray[a]=malloc(sizeof(**StructArray) * NumberOfColumns);
if (StructArray[a]==NULL) return 1;
}
for (a=0; a<NumberOfRows; a++)
{ for (b=0; b<NumberOfColumns; b++)
{ memset(StructArray[a].test, '\0', NUMBER);
strncpy(StructArray[a].test, ctest, len);
StructArray[a].length=len;
}
}
for (a=0; a<NumberOfRows; a++)
{ for (b=0; b<NumberOfColumns; b++)
{ printf("{%d,%d} %s %d\n", a, b, StructArray[a].test,
StructArray[a].length);
}
}
return 0;
}
Output:
4 104
{0,0} test 4
{0,1} test 4
{1,0} test 4
{1,1} test 4
{2,0} test 4
{2,1} test 4
{3,0} test 4
{3,1} test 4
Is the code above correct?
Is there an alternative way of allocating the required space for the
array? This has a lot of malloc calls, and I wonder if it can be done
more efficiently.
Thanks
Qued
#define NUMBER 100
#include <stdlib.h>
struct sData
{ char test[NUMBER];
int length;
};
int main(int argc, char *argv[])
{ int a, b;
int NumberOfRows=4, NumberOfColumns=2;
char ctest[]="test";
struct sData **StructArray=NULL;
int len=strlen(ctest);
printf("%d %d\n", sizeof(*StructArray), sizeof(**StructArray));
StructArray=malloc(sizeof(*StructArray) * NumberOfRows);
if (StructArray==NULL) return 1;
for (a=0; a<NumberOfRows; a++)
{ StructArray[a]=malloc(sizeof(**StructArray) * NumberOfColumns);
if (StructArray[a]==NULL) return 1;
}
for (a=0; a<NumberOfRows; a++)
{ for (b=0; b<NumberOfColumns; b++)
{ memset(StructArray[a].test, '\0', NUMBER);
strncpy(StructArray[a].test, ctest, len);
StructArray[a].length=len;
}
}
for (a=0; a<NumberOfRows; a++)
{ for (b=0; b<NumberOfColumns; b++)
{ printf("{%d,%d} %s %d\n", a, b, StructArray[a].test,
StructArray[a].length);
}
}
return 0;
}
Output:
4 104
{0,0} test 4
{0,1} test 4
{1,0} test 4
{1,1} test 4
{2,0} test 4
{2,1} test 4
{3,0} test 4
{3,1} test 4
Is the code above correct?
Is there an alternative way of allocating the required space for the
array? This has a lot of malloc calls, and I wonder if it can be done
more efficiently.
Thanks
Qued