My question is very simple, but I still can't manage to get things right because I am simply not used to the C language.
I have an array that looks like this:
char *itemArr[] = {
"GPGGA",
"193914.00",
"5312.983745",
"N",
"00206.32143",
"E",
"4,17",
"0.6",
"43.48",
"M",
"47.46",
"M",
"1.0",
"0000",
"GPGLL,4916.45,N,12311.12,W,225444,A,M"
};
And I would like to add itemArr to a new multidimensional array, but when I try to copy the content of itemArr to protocols array like this:
int index = 0;
char *protocols[100][TOTAL_ITEMS];
memcpy(&protocols[index++], &itemArr, sizeof(itemArr));
It does only copy the first item of the itemArr and not the rest. So I can only see the first item like the following code:
printf("itemArr copy in protocols - index 0: %s\n", protocols[0][0]);
For example, this does not work:
printf("itemArr copy in protocols - index 1: %s\n", protocols[0][1]);
Please help me with a better example of how I should use memcpy, to copy an array to a multidimensional array. Thanks!
EDIT:
I tried my best to explain the code as simple as possible, but I guess that it only helps when pasting the real one below:
void getInputProtocolFromUser(protocol) {
char input[MESSAGE_SIZE];
do {
printf("Voer hier een NMEA protocol in:");
gets(input, MESSAGE_SIZE);
} while (input[0] == '\*' || input[0] == ' ');
strncpy_s(protocol, MESSAGE_SIZE, input, MESSAGE_SIZE);
}
void splitToArray(char* protocol, char *newArray[]) {
// strdup copies message to string pointer in order to create an array of the items inside the message
char *string = _strdup(protocol),
*token;
int c = 0;
/* get the first token */
token = strtok(string, ",");
/* walk through other tokens */
while (token != NULL)
{
char *copy = malloc(sizeof(char) * strlen(token));
strcpy(copy, token);
newArray[c++] = copy;
token = strtok(NULL, ",");
}
}
void compareProtocols(char *input, char *protocols[]) {
int index = 0;
char *inputArray[TOTAL_ITEMS+1];
splitToArray(input, inputArray);
inputArray[TOTAL_ITEMS] = input;
memcpy(&protocols[index++], &inputArray, 15);
int i;
for (i = 0; i < sizeof(MESSAGES) / sizeof(MESSAGES[0]); i++) {
char *messageArray[TOTAL_ITEMS];
splitToArray(MESSAGES[i], messageArray);
memcpy(&protocols[index++], &messageArray, 15);
//processProtocol(messageArray, inputArray);
}
}
int main(void) {
char *protocols[100][TOTAL_ITEMS];
char *inputProtocol = (char *)malloc(MESSAGE_SIZE);
getInputProtocolFromUser(inputProtocol);
compareProtocols(inputProtocol, protocols);
printf("Input index 0: %s\n", protocols[0][1]);
free(inputProtocol);
return 0;
}