Can I take a word out of Array of strings?

94 Views Asked by At

I am writing the following string in the main function:

char* dict[] = { "ball", "aba", "bla" };

My question is:

Am I able to take a whole word out of this string?

For example, if I want to copy the whole word, can I do something like this: str[j] = dict[i]; (in some loop of course)

It is important to note that I can't use the #include<string.h> library, due to the requirements of the question

1

There are 1 best solutions below

0
On

A string in C is "Null terminated". It's actually an array of char ended by "0". For example, we have:

char* str = "abc";

This statement will create an array of 4 elements, 'a', 'b', 'c', 0, and str is the pointer to the array (or pointer to the first element of the array). And the value of str is just an address, which is just an integer number. If you copy the string in the way of str[j] = dict[i] you copy only the address (shallow copy). It will not duplicate the string.

In your case, you create a list of strings (array of char), and dict[i] is the pointer to the first element of the i-th string. In other words, we can handle dict[i] like a regular string (e.g. str in my example).

This is an example of creating a deep copy of your list.

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

int main() {
    char* dict[] = { "ball", "aba", "bla" };
    char** copy = (char**) malloc((3) * sizeof(char*));
    for (int i=0; i<3; i++) {
        char *shallowCopy = dict[i];
        int length = 0;
        
        while (shallowCopy[length] != 0) length ++; // find the length of the string
        // printf("length: %d\n", length);
        
        char *deepCopy = (char*) malloc((length + 1) * sizeof(char)); // +1 for null terminated
        deepCopy[length] = 0; // null terminated
        
        while(length >0) deepCopy[--length] = shallowCopy[length];

        copy[i] = deepCopy; // is deepCopy what you mean "to take a whole word out of this string (list)"?
    }
    
    for (int i=0; i<3; i++) {
        printf("%s\n", copy[i]);
    }   
}