Reputation: 104
I am using the C programming language. I currently have a two dimensional character array of dates in this format "2010-05-01". I would like to convert each number into the integer data type and then store them in an integer array. The reason for this is because I need to have an single dimensional array of integers that I can then pass to a function by reference using pointers.
Please see my 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 a total of 100 dates}
int dates[size * 3];
for (i = 0, j = 0; j < size; ++i, ++j) {
dates[i] = atoi(strtok(strings[j], "-"));
dates[++i] = atoi(strtok(NULL, "-"));
dates[++i] = atoi(strtok(NULL, "-"));
}
for (i = 0; i < size; ++i)
printf("%d\n", dates[i]);
return 0;
}
This code currently returns a bus error and I do not see why. I am a relative beginner, so sorry if I have done something silly. Any comments would be appreciated and thank you for your time.
Upvotes: 2
Views: 1460
Reputation: 15328
To extract independently the year, the day and the month and putting them in a same array, you can put together the years, followed by the months and then the days (supposing that a date is formated as yyyy-mm-dd
). Such an array could store the following sequence:
y1, y2, y3, m1, m2, m3, d1, d2, d3
The following code do that kind of thing in the 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];
for (i = 0; i < SIZE; i++) {
ymd[i*3] = atoi(strtok(strings[i], "-"));
ymd[i*3+1] = atoi(strtok(NULL, "-"));
ymd[i*3+2] = atoi(strtok(NULL, "-"));
}
for (i = 0; i < SIZE; i++)
printf("%d/%d/%d\n", ymd[i*3], ymd[i*3+1], ymd[i*3+2]);
return 0;
}
The output will be:
2010/5/1
2010/10/1
Upvotes: 1
Reputation: 5132
char strings[][10]
should be char strings[][11]
to take the trailing null character into account.
You seem to be parsing each date into three entries into the dates
array -- is that the intention?
Upvotes: 1