C
Christopher Benson-Manica
The thread where casting is being discussed motivated me to try this. Let's
say you wanted to populate a BankRecord structure (as I defined below) with
17-character record numbers, but with the record numbers separated into a SSN
and an account number (and with a terminating '\0')...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char SSN[9];
char AccountNum[8];
char end;
} BankRecord;
int main( int argc, char * argv[] )
{
int i;
BankRecord *a;
if( argc < 2 ) {
printf( "No information provided\n" );
return EXIT_FAILURE;
}
if( (a=malloc((argc-1)*(sizeof(BankRecord)))) == NULL ) {
printf( "Malloc() failed\n" );
return EXIT_FAILURE;
}
for( i=1; i < argc; i++ ) {
snprintf( (char*)&a[i-1], sizeof(BankRecord), "%s", argv );
}
for( i=0; i < argc-1; i++ ) {
printf( "%s\n", (char*)&a ); /* just to prove that it works */
}
return EXIT_SUCCESS;
}
1) Is this code legal C? (it compiled with no warnings for me and worked
correctly)
2) Is the cast of a structure to a char* the best way to solve this contrived
problem?
3) How can I declare BankRecord in such a way so that end is a const char
equal to '\0'? Would that be desirable?
4) Any other comments?
say you wanted to populate a BankRecord structure (as I defined below) with
17-character record numbers, but with the record numbers separated into a SSN
and an account number (and with a terminating '\0')...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char SSN[9];
char AccountNum[8];
char end;
} BankRecord;
int main( int argc, char * argv[] )
{
int i;
BankRecord *a;
if( argc < 2 ) {
printf( "No information provided\n" );
return EXIT_FAILURE;
}
if( (a=malloc((argc-1)*(sizeof(BankRecord)))) == NULL ) {
printf( "Malloc() failed\n" );
return EXIT_FAILURE;
}
for( i=1; i < argc; i++ ) {
snprintf( (char*)&a[i-1], sizeof(BankRecord), "%s", argv );
}
for( i=0; i < argc-1; i++ ) {
printf( "%s\n", (char*)&a ); /* just to prove that it works */
}
return EXIT_SUCCESS;
}
1) Is this code legal C? (it compiled with no warnings for me and worked
correctly)
2) Is the cast of a structure to a char* the best way to solve this contrived
problem?
3) How can I declare BankRecord in such a way so that end is a const char
equal to '\0'? Would that be desirable?
4) Any other comments?