Reputation: 25
This is a continuation of my last question.
So far, I've successfully taken user input and stored it into strings. For example, I turned this:
1:E 2:B 2:B 2:B 4:G
Into this:
1:E
2:B
2:B
2:B
4:G
Which is an array of strings.
This is what I want to do next, but it's not working for me:
1
E
2
B
2
B
2
B
4
G
And each of these would be characters stored into an array of characters.
Here's the chunk of code I've got working correctly:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INPUT_SIZE ( (sizeof(char)*96) + (sizeof(int)*48) )
int main () {
char *input = malloc(MAX_INPUT_SIZE);
printf("Example input: 1:E 2:C 2:C 2:C 8:D\n");
printf("Your input:\n\n");
fgets(input, MAX_INPUT_SIZE, stdin);
// Removing newline
if ( (strlen(input) > 0) && (input[strlen(input) - 1] == '\n') )
input[strlen(input) - 1] = '\0';
int i = 0;
char *p = strtok(input, " ");
char *array[MAX_PAIRS];
while (p != NULL){
array[i++] = p;
p = strtok(NULL, " ");
}
// Checking the array
int j = 0;
for (j=0; j<i; j++) {
printf("\n %s", array[j]);
}
And this code works just fine. Next is the code I'm currently working with:
int k = 0;
int l = 0;
char *letter = malloc( sizeof(char) * (i * 2) );
for (k=0; k<i; k++) {
char *q = strtok(array[k], ":");
while (q != NULL) {
letter[l++] = q;
q = strtok(NULL, ":");
}
}
// Checking the array
int m = 0;
for (m=0; m<l; m++) {
printf("\n %c", letter[m]);
}
return 0;
}
When I go to check the array, it prints a garbage symbol for each character I wanted to print. I don't understand what I did wrong here.
Upvotes: 0
Views: 543
Reputation: 1619
letter
is an array of char
.
q
is a char*
.
Therefore, letter[l++] = q
is not going to do what you want, as you're now storing a char*
into a char
; I would imagine the compiler would spit out some warning about truncation.
Upvotes: 1