0

I was wondering that if someone gave me an input file of many words:

Such as: "AB1CDE1 FG2HIJ2 KL3MNO3"

and I wanted to put each word into a char array in which the resulting outputs would be:

printing this ->

  • array[0] = "AB1CDE1"
  • array[1] = "FG2HIJ2"
  • array[2] = "KL3MNO3"

I would need to allocate memory for this is what I understand.

So if I use char *array = (char*)malloc(sizeof(*array) * num_arrays) wouldn't this only give me the first values of each input given to me?

How would I initialize this array to store all the values in each array?

(I'm new to C coding so might be a really easy question.)

1 Answer 1

1

You can use pointer to array of chars, and then allocate enough space with malloc for that.

Code Example

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char (*array)[8] = malloc(3u * sizeof(char [8]));

    strcpy(array[0], "AB1CDE1");
    strcpy(array[1], "FG2HIJ2");
    strcpy(array[2], "KL3MNO3");

    printf("array[0] = %s\n", array[0]);
    printf("array[1] = %s\n", array[1]);
    printf("array[2] = %s\n", array[2]);

    free(array);
    return 0;
}

Run

ammarfaizi2@integral:/tmp$ gcc test.c -o test
ammarfaizi2@integral:/tmp$ ./test
array[0] = AB1CDE1
array[1] = FG2HIJ2
array[2] = KL3MNO3
Sign up to request clarification or add additional context in comments.

4 Comments

What does the 3u mean when using malloc? Is it specifically the numbers that I am using? I understand the 3 but not the u
The u means "unsigned int", you don't need it. malloc(3 * ... is enough.
Yeah, it is unsigned int. Not strictly required, it is just my habit to emphasize that the argument is unsigned type.
I prefer char (*array)[8] = malloc(3u * sizeof *array); so that there's only one place to change when you need longer strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.