Sunday, 15 March 2015

c - Convert Array of Dates into Integers -



c - Convert Array of Dates into Integers -

i using c programming language. have 2 dimensional character array of dates in format "2010-05-01". convert each number integer info type , store them in integer array. reason because need have single dimensional array of integers can pass function reference using pointers.

please see current code below:

#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> int main() { float values[] = { //contains 100 float literals } int i, j, size = sizeof(values)/sizeof(*values); char strings[][10] = {"2010-05-01", "2010-10-01" //contains total of 100 dates} int dates[size * 3]; (i = 0, j = 0; j < size; ++i, ++j) { dates[i] = atoi(strtok(strings[j], "-")); dates[++i] = atoi(strtok(null, "-")); dates[++i] = atoi(strtok(null, "-")); } (i = 0; < size; ++i) printf("%d\n", dates[i]); homecoming 0; }

this code returns bus error , not see why. relative beginner, sorry if have done silly. comments appreciated , give thanks time.

to extract independently year, day , month , putting them in same array, can set years, followed months , days (supposing date formated yyyy-mm-dd). such array store next sequence:

y1, y2, y3, m1, m2, m3, d1, d2, d3

the next code kind of thing in array ymd

#include <stdio.h> #include <stdlib.h> #include <string.h> #define size 2 int main() { int i; char strings[size][11] = {"2010-05-01", "2010-10-01" }; int ymd[size*3]; (i = 0; < size; i++) { ymd[i*3] = atoi(strtok(strings[i], "-")); ymd[i*3+1] = atoi(strtok(null, "-")); ymd[i*3+2] = atoi(strtok(null, "-")); } (i = 0; < size; i++) printf("%d/%d/%d\n", ymd[i*3], ymd[i*3+1], ymd[i*3+2]); homecoming 0; }

the output be:

2010/5/1 2010/10/1

c arrays pointers char type-conversion

No comments:

Post a Comment