Нарушение прав доступа при чтении по адресу - C (СИ)

Узнай цену своей работы

Формулировка задачи:

Здраствуйте, задано переписать функцию strspn(canst char *s1, const char *s2) так чтоб она искала самый длинный фрагмент строчки s1, содержащий только елементы строчки s2, при этом фрагмент не обязательно расположен в начале строчки. Признаюсь честно я не сильно дружу з си(особенно с указателями), но пришлось вспоминать чтоб сделать задание. Значит выбрал я следующий алгоритм: сравниваем каждый елемент строчки s1 со всеми елементами строчки s2, находя совпадение запускаем рекурсивно функцию подсчета фрагмента одинаковых елементов от оставшейся части строчки s1 и строчки s2. Ошифка возникает при выделении оставшейся части строчки s1 в строке 56 Сперва подумал про возможный выход за пределы, сделал обработчик через if перед переписыванием, но ошибка осталась. (так же уверен что в строке 25 будет такая же ошибка, но програма туда просто не доходит пока) Подскажите что может быть не верно и где исправить или же как оптимизировать даный кусок коду.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale>
 
int temp = 0;
int max = 0;
 
void count(const char *s1, const char *s2)
{
    temp++;
    int i, j;
    for (i = 0; i < strlen(s2); i++)
    {
        if ((s1[0] == s2[i]) && (s2[i] != '\n'))
        {
            int i1;
            char s1_tmp[100];
            int k = 0;
            if (1 < strlen(s1))
            {
                for (i1 = 1; i < strlen(s1); i1++)
                {
                    s1_tmp[k] = s1[i1];
                    k++;
                }
                count(s1_tmp, s2);
            }
            else
            {
                count((const char*)s1[0], s2);
            }
        }
    }
    if (temp > max) max = temp;
    temp = 0;
}
 
void StrSpn(const char *s1, const char *s2)
{
    const char *start = s1;
    int i, j;
    for (i = 0; i < strlen(s1); i++)
    {
        for (j = 0; j < strlen(s2); j++)
        {           
            if ((s1[i] == s2[j]) && (s1[i] != '\n'))
            {
                int i1;
                char s1_tmp[100];
                int k = 0;
                if (i + 1 < strlen(s1)) {
                    for (i1 = i + 1; i < strlen(s1); i1++)
                    {
                        s1_tmp[k] = s1[i1];
                        k++;
                    }
                    count(s1_tmp, s2);
                }
                else
                {
                    count((const char*)s1[i], s2);
                }
            }
        }
    }
}
 
int main()
{
    setlocale(LC_ALL, "ukr");
    char s[100];
    char s1[100];
    int i, cur = 0;
    printf("Enter first string: ");
    fgets(s, 80, stdin);
    char sfirst = s[0];
    if (sfirst == '\n') {
        printf("Error! Empty string!");
    }
    else
    {
        printf("Enter second string: ");
        fgets(s1, 80, stdin);
        char s1first = s1[0];
        if (s1first == '\n') {
            printf("Error! Empty string!");
        }
        else
        {
            StrSpn(s, s1);
            printf("Result: %d\n", max);
        }
    }
 
    system("pause");
    return 0;
}

Решение задачи: «Нарушение прав доступа при чтении по адресу»

textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale>
 
int temp = 0;
int max = 0;
 
void count(const char *s1, const char *s2)
{
    temp++;
    int i, j;
    for (i = 0; i < strlen(s2); i++)
    {
        if ((s1[0] == s2[i]) && (s2[i] != '\n'))
        {
            int i1;
            char s1_tmp[100] = { NULL };
            int k = 0;
            int t = strlen(s1);
            if (1 < strlen(s1))
            {
                for (i1 = 1; i1 < strlen(s1); i1++)
                {
                    s1_tmp[k] = s1[i1];
                    k++;
                }
                count(s1_tmp, s2);
            }
            else
            {
                count((const char*)s1[0], s2);
            }
        }
    }
    if (temp > max) max = temp;
    temp = 0;
}
 
void StrSpn(const char *s1, const char *s2)
{
    const char *start = s1;
    int i, j;
    for (i = 0; i < strlen(s1); i++)
    {
        for (j = 0; j < strlen(s2); j++)
        {
            if ((s1[i] == s2[j]) && (s1[i] != '\n'))
            {
                int i1;
                char s1_tmp[100] = { NULL };
                int k = 0;
                if (i + 1 < strlen(s1)) {
                    for (i1 = i + 1; i1 < strlen(s1); i1++)
                    {
                        s1_tmp[k] = s1[i1];
                        k++;
                    }
                    count(s1_tmp, s2);
                }
                else
                {
                    count((const char*)s1[i], s2);
                }
            }
        }
    }
}
 
int main()
{
    setlocale(LC_ALL, "ukr");
    char s[100];
    char s1[100];
    int i, cur = 0;
    printf("Enter first string: ");
    fgets(s, 80, stdin);
    char sfirst = s[0];
    if (sfirst == '\n') {
        printf("Error! Empty string!");
    }
    else
    {
        printf("Enter second string: ");
        fgets(s1, 80, stdin);
        char s1first = s1[0];
        if (s1first == '\n') {
            printf("Error! Empty string!");
        }
        else
        {
            StrSpn(s, s1);
            printf("Result: %d\n", max);
        }
    }
 
    system("pause");
    return 0;
}

Оцени полезность:

7   голосов , оценка 3.571 из 5
Похожие ответы