Создайте функцию, которая возвращает массив, в котором каждая ячейка содержит адрес строки (представляющей слово) - PullRequest
0 голосов
/ 19 марта 2020

Мне нужен совет относительно этого упражнения по кодированию:

Напишите функцию, которая разбивает строку на слова. Все разделители будут состоять не из букв c. Функция возвращает массив, в котором каждая ячейка содержит адрес строки (представляющей слово). Последняя ячейка должна быть NULL для завершения массива.

Мне нужна помощь в двух вещах: как моя функция правильно возвращает массив моей главной функции и выполняет ли массив mallo c используется правильно?

Я думаю, что пропустил части указателя, потому что во время компиляции появляются ошибки. Если у вас есть идеи, пожалуйста, дайте мне знать, спасибо!

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

char **my_str_to_word_array(const char *str)
{
    char* tab_address = NULL;
    int j = 0; /*Nombre de mots*/
    int i = 0;
    char ptr = 0;

    for( i = 0; str[i] != " "; i++)/*Compter le nombre de mots dans la string*/
        if(*str[i] = " ")
            j++;

    tab_address = malloc(sizeof(char) * j); /*tab avec tous les mots compter par j*/
    if (tab_address == NULL)
        exit(0);

    for ( i = 0; str[i] != " "; i++) /*Stocker les adresse dans un tableau */
        if(str[i] = " ")
        {
            i++;
            tab_address[j] = ptr;
        }
        else if (*str[i] = "\0")
            break;

    return ptr;
    free(tab_address);
}

int main(void)
{
    char str[50] = "Hello world";
    my_str_to_word_array(str);

    return 0;
}

1 Ответ

0 голосов
/ 19 марта 2020

Кажется, работает. Обратите внимание, что код предполагает, что str не является NULL.

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h> // added for usage of isalpha function

char **my_str_to_word_array(const char *str)
{
    char** tab_address = NULL; // FIXED: this need to be an array of char* so char**
    int j = 0; /*Nombre de mots*/
    int i = 0;
    //char ptr = 0; // FIXED: This not needed

    for(i = 0; str[i] != '\0'; i++) // FIXED: you want to go until the end of the string
        if(isalpha(str[i])) // FIXED: you want to check for non alphanumeric here not space
            j++;

    tab_address = malloc(sizeof(char*) * (j + 1)); // FIXED: you want to allocate char* -s not char -s
    if (tab_address == NULL)
        exit(0);

    tab_address[0] = str; // ADDED: the first word should be at the start of the string
    j = 1; // FIXED: reinitialize j to 1
    for ( i = 0; str[i] != '\0'; i++) // FIXED: you want to go until the end of the string 
        if(!isalpha(str[i])) // FIXED: you want to check for non alphanumeric here not space
            tab_address[j++] = &str[++i]; // setting the next pointer to the next words address
        //else if (*str[i] = "\0")  // FIXED: these can be deleted
        //    break;

    tab_address[j] = NULL; // ADDED: setting the last element to NULL
    return tab_address; // FIXED: you want to return the char** array not ptr
    // free(tab_address); // FIXED: this is dead code, and you want to free it later anyway
}

int main(void)
{
    char str[50] = "Hello There World";
    char ** result = my_str_to_word_array(str);
    char ** for_freeing = result; // save the start address of the result to later free it

    while (*result != NULL)
    {
        printf("%s\n", *result);
        result++;
    }

    free(for_freeing);

    return 0;
}

Вывод

Hello There World
There World
World

Что на самом деле правильно, если вы об этом думаете.

...