I am converting (from javascript) a program that will take a string of variable length (but always under 100 char) and return the data contained in the string in individual variables. This is the first portion of my code, and obviously, I am new to C and programming in general. This code is for the first section of the code, but learning how to properly code this would give me the know how to code the rest.
I need:
- the first 4 digits to be stored as 'stringID'
- the 5th digit to be stored as 'myindicator'
- the 6th through (indicator + 6) digits to be stored as 'var1'
Example input:
'12345678901234567890123'
Example output:
- stringID = 1234
- myindicator = 5
- var1 = 67890123456
When I run the program, it returns 'String ID: H>a' and then the program crashes. Any help would be appreciated. No, this is not homework.
int main()
{
char mystring[100];
char *stringID;
int nep;
int *myindicator;
char *var1;
nep = 0;
printf("Please enter your CODE\n");
scanf("%s", &mystring);
stringID = (char *)malloc(4 * sizeof(char));
if(NULL != stringID)
{
strncpy(stringID, mystring, 4);
stringID[4] = '\0';
free(stringID);
nep = nep +4;
printf("stringID: %s\n",myindicator);
}
if(NULL != myindicator)
{
strncpy(myindicator, (mystring+nep, 1);
nep++;
myindicator = *myindicator - '0';
printf("Indicator : %d\n",myindicator);
}
var1 = (char *)malloc((nep + 6) * sizeof(char));
if(NULL != var1)
{
strncpy(var1, mystring+nep, (myindicator+nep+6));
var1[myindicator+nep+6] = '\0';
free(var1);
printf("Var 1: %s", var1);
nep = nep +myindicator+6;
}
getchar();
return 0;
}