0

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

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Omer Zohar
  • 27
  • 2
  • 3
    Before diving in further, do you understand that isn't a "array of strings", it's an array of *pointer-to-char* ? It's important. Further making copies of a "whole word" can take on different meaning, depending on whether you want to copy the *pointer* to string data vs. copy the string data itself. Assuming `str` is an array of `char*`, `str[j] = dict[i]` can work, but will not make a copy of the string data as you may desire; it will simply copy the pointer to that data to another location, thereby having multiple pointers referring to the same underlying memory. – WhozCraig Jul 16 '20 at 18:24
  • 1
    @Omer Zohar How is the array str declared? i – Vlad from Moscow Jul 16 '20 at 18:33

1 Answers1

2

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]);
    }   
}
TucoMoc
  • 21
  • 3