Форум программистов, компьютерный форум, киберфорум
C для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.94/18: Рейтинг темы: голосов - 18, средняя оценка - 4.94
0 / 0 / 1
Регистрация: 13.07.2013
Сообщений: 14
1

Ошибка Debug Asserition Failed Expression:(stream !=NULL)

13.07.2013, 10:40. Показов 3719. Ответов 16
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Задание: Написать графф и в нем реализовать алгоритм Дейкстры и обход в ширину и высоту. (Прикрепляю код и скрин с ошибкой) помогите, кто сможет. Задание по практике нужно уложиться до 16.07
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
 
 
 
 
 
 
int g[1000][1000]; // граф
int n; // число вершин
int s; // стартовая вершина (вершины везде нумеруются с нуля)
int v_dfs[1000];int i_v_dfs;
int used1[1000];
int v_bfs[1000][1000]={0}; int i_v_bfs;
int used[500]={0};//массив использованных вершин
int d[500]={0};//массив длин пути
int inf=1000000000;//условная бесконечность
 
void dfs(int node_index)
{
    int i;
    used1[node_index] = 1;
    v_dfs[i_v_dfs]=node_index;
    i_v_dfs=i_v_dfs+1;
    for (i=0; i<n; ++i)
    {
        if (g[node_index][i] && !used1[i])
            dfs(i);
    }
}
 
void input_graf()
{
    FILE *in;
    int i,j;
    in=fopen("in.txt","r");
    
    i_v_dfs=i_v_dfs=0;
 
    
 
    fscanf(in,"%d",&n);
 
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            fscanf(in,"%d",&g[i][j]);
 
 
    for(i=0;i<n;i++)
        used1[i]=0;
}
 
void bfs(int start)
{
    int visited[1000],i,j;
    int curr;
    int queue[1000];
    int r = 0, w = 1;
    for(i=0;i<n;i++)
        visited[i]=0;
    
 
    queue[0] = start;
    visited[start] = 1;
    
 
 
    while (r < w) 
    {
        curr = queue[r++];
        for (i = 0; i < n; i++)
            if (!visited[i] && g[curr][i]) 
            {
                visited[i] = 1;
                queue[w++] = i;
                v_bfs[i_v_bfs][v_bfs[i_v_bfs][0]+1]=i+1;
                v_bfs[i_v_bfs][0]++;
            }
        i_v_bfs++;
    }
}
 
void deikstr(int v1,int v2)
{
        int m,x=0,y=0,z=0,i,j,to;
 
    m=n;
 
    for (i=0;i<n;i++) 
        d[i]=inf;
 
    d[v1]=0;
    while (1){
    int from,zfrom=inf;
        for (i=0;i<n;i++)
            if ((zfrom>d[i]) && !(used[i])) {from=i;zfrom=d[i];}
            if (zfrom>=inf) break;
            used[from]=1;
        for(to=0;to<n;to++)
            if (g[from][to]!=0) 
                if ((!used[to]) && (d[to]>d[from]+g[from][to])) d[to]=d[from]+g[from][to];
        }
    if (d[v2]<inf) printf("%d",d[v2]);else printf("Нет пути!");
}
 
 
 
int main()
{
    int i,j,a,b;
    input_graf();
 
    dfs(0);
    printf("Poisk v glubinu(istoriya puti):\n");
    for(i=0;i<n;i++)
        printf("%d\t",v_dfs[i]+1);  
    
    printf("\n\nPoisk v shirinu(vivod vershin po stepeni udalennosti ot pervoy):\n");
    bfs(0);
    for(i=0;i<i_v_bfs;i++)
    {
        if(v_bfs[i][0]!=0)
            for(j=1;j<v_bfs[i][0]+1;j++)
                printf("%d\t",v_bfs[i][j]);
 
        printf("\n");
    }
    
    a=1;b=3;
    printf("\nDlina kratchaishego puti ot vershini %d do vershini %d: ",a+1,b+1);
    deikstr(a,b);
    printf("\n\n");
 
    return 0;
}
вот скрин с ошибкой
Миниатюры
Ошибка Debug Asserition Failed Expression:(stream !=NULL)  
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
13.07.2013, 10:40
Ответы с готовыми решениями:

Debug Assertion Failed! Expression: is_block_type_valid(header- _block_use)
Всем доброго времени суток! Столкнулся с проблемой при удалении элементов из двусвязного списка....

Debug Assertion failed. Line 77. Expression (stream!=0)
Подскажите, пожалуйста, в чем заключается ошибка. Запускается, начинает работать, а потом пишет...

Expression:(Stream != NULL)
Помогите решить проблему, не понимаю в чем ошибка #define _CRT_SECURE_NO_WARNINGS #include...

Debug asserion failed(expression:_p!=nullptr)
Не понимаю в чем ошибка,вылетает на 183 строке #include &quot;stdafx.h&quot; #include &lt;iostream&gt;...

16
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12458 / 7482 / 1753
Регистрация: 25.07.2009
Сообщений: 13,762
13.07.2013, 13:50 2
BlaMe64, вот, почему так здорово проверять, что возвращают функции вообще и fopen() в частности. 38 строка
C
1
2
3
if ( ! ( in = fopen("in.txt", "r") ) ) {
    /* обработать ошибку открытия файла */
}
0
0 / 0 / 1
Регистрация: 13.07.2013
Сообщений: 14
13.07.2013, 13:58  [ТС] 3
Цитата Сообщение от easybudda Посмотреть сообщение
BlaMe64, вот, почему так здорово проверять, что возвращают функции вообще и fopen() в частности. 38 строка
C
1
2
3
if ( ! ( in = fopen("in.txt", "r") ) ) {
    /* обработать ошибку открытия файла */
}
его что то не устраивает вот в 44 строке именно на нее указывает
C
1
fscanf(in,"%d",&n);
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12458 / 7482 / 1753
Регистрация: 25.07.2009
Сообщений: 13,762
13.07.2013, 14:02 4
BlaMe64, попробую угадать, что именно: файл не открылся, значение in равно NULL
0
0 / 0 / 1
Регистрация: 13.07.2013
Сообщений: 14
13.07.2013, 14:30  [ТС] 5
Цитата Сообщение от easybudda Посмотреть сообщение
BlaMe64, попробую угадать, что именно: файл не открылся, значение in равно NULL
там на скрине все видно, после того,как закрываю отладку, показывает на 44 строку

Добавлено через 5 минут
Цитата Сообщение от easybudda Посмотреть сообщение
BlaMe64, попробую угадать, что именно: файл не открылся, значение in равно NULL
если сможете помогите с правильным построением кода...а то у меня уже мозг вскипает><
0
26 / 26 / 7
Регистрация: 05.04.2012
Сообщений: 248
13.07.2013, 15:10 6
Цитата Сообщение от easybudda Посмотреть сообщение
BlaMe64, вот, почему так здорово проверять, что возвращают функции вообще и fopen() в частности. 38 строка
C
1
2
3
if ( ! ( in = fopen("in.txt", "r") ) ) {
    /* обработать ошибку открытия файла */
}
Вы последовали этому совету?
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12458 / 7482 / 1753
Регистрация: 25.07.2009
Сообщений: 13,762
13.07.2013, 17:54 7
BlaMe64, оно и так заработает, если файл с входными данными в "правильное" место положить.
Наверное заработает... Если ошибок нет...

Добавлено через 2 минуты
Цитата Сообщение от BlaMe64 Посмотреть сообщение
там на скрине все видно, после того,как закрываю отладку, показывает на 44 строку
А 44 строку на скрине отсчитать надо? Номера строк в настройках редактора включить - не?
0
0 / 0 / 1
Регистрация: 13.07.2013
Сообщений: 14
14.07.2013, 11:45  [ТС] 8
Цитата Сообщение от easybudda Посмотреть сообщение
BlaMe64, оно и так заработает, если файл с входными данными в "правильное" место положить.
Наверное заработает... Если ошибок нет...

Добавлено через 2 минуты

А 44 строку на скрине отсчитать надо? Номера строк в настройках редактора включить - не?
я имею ввиду в моем сообщении в коде она 44
0
4064 / 3318 / 924
Регистрация: 25.03.2012
Сообщений: 12,492
Записей в блоге: 1
14.07.2013, 13:54 9
Да создай ты уже файл in.txt в нужном месте! Больше суток прошло, а ты всё файл не создашь!
0
0 / 0 / 1
Регистрация: 13.07.2013
Сообщений: 14
15.07.2013, 00:00  [ТС] 10
Цитата Сообщение от Kuzia domovenok Посмотреть сообщение
Да создай ты уже файл in.txt в нужном месте! Больше суток прошло, а ты всё файл не создашь!
ну если ты такой остряк то сообщаю файл создан и лежит в папке с ресурсами!
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12458 / 7482 / 1753
Регистрация: 25.07.2009
Сообщений: 13,762
15.07.2013, 01:09 11
Цитата Сообщение от BlaMe64 Посмотреть сообщение
ну если ты такой остряк то сообщаю файл создан и лежит в папке с ресурсами!
ну так переложи его в папку с исполняемым файлом, или в корень проекта - откуда-нибудь, да подцепится.
0
26 / 26 / 7
Регистрация: 05.04.2012
Сообщений: 248
15.07.2013, 01:20 12
Короче, вместо того, чтобы искать, где же должен лежать этот файл (возможно там же где и исходник), укажи абсолютный путь к этому файлу и будет тебе счастье.
0
Модератор
Эксперт PythonЭксперт JavaЭксперт CЭксперт С++
12458 / 7482 / 1753
Регистрация: 25.07.2009
Сообщений: 13,762
15.07.2013, 01:36 13
Цитата Сообщение от main.c Посмотреть сообщение
Короче, вместо того, чтобы искать, где же должен лежать этот файл (возможно там же где и исходник), укажи абсолютный путь к этому файлу и будет тебе счастье.
Ну или так. Тогда предугадывая следующий вопрос: обратные слеши в имени файла должны удваиваться: "disk:\\folder\\file"
0
Заблокирован
15.07.2013, 01:44 14
Цитата Сообщение от BlaMe64 Посмотреть сообщение
ну если ты такой остряк то сообщаю файл создан и лежит в папке с ресурсами!
а исполняемый файл (тот, который *.exe) тоже "в папке с ресурсами"?
0
0 / 0 / 1
Регистрация: 13.07.2013
Сообщений: 14
15.07.2013, 11:42  [ТС] 15
Цитата Сообщение от duhast_vladisla Посмотреть сообщение
а исполняемый файл (тот, который *.exe) тоже "в папке с ресурсами"?
он в папке debug
0
Заблокирован
15.07.2013, 16:21 16
Цитата Сообщение от BlaMe64 Посмотреть сообщение
он в папке debug
ну и теперь скрипя шестеренками пытаемся прийти к умозаключениям.

Добавлено через 4 минуты
fopen
Код
fopen(3)                 BSD Library Functions Manual                 fopen(3)


NAME

     fdopen, fopen, freopen -- stream open functions


LIBRARY

     Standard C Library (libc, -lc)


SYNOPSIS

     #include <stdio.h>

     FILE *
     fdopen(int fildes, const char *mode);

     FILE *
     fopen(const char *restrict filename, const char *restrict mode);

     FILE *
     freopen(const char *restrict filename, const char *restrict mode,
         FILE *restrict stream);


DESCRIPTION

     The fopen() function opens the file whose name is the string pointed to
     by filename and associates a stream with it.

     The argument mode points to a string beginning with one of the following
     sequences (Additional characters may follow these sequences.):

     "r"   Open text file for reading.  The stream is positioned at the
             beginning of the file.

     "r+"  Open for reading and writing.  The stream is positioned at the
             beginning of the file.

     "w"   Truncate to zero length or create text file for writing.  The
             stream is positioned at the beginning of the file.

     "w+"  Open for reading and writing.  The file is created if it does not
             exist, otherwise it is truncated.  The stream is positioned at
             the beginning of the file.

     "a"   Open for writing.  The file is created if it does not exist.  The
             stream is positioned at the end of the file.  Subsequent writes
             to the file will always end up at the then current end of file,
             irrespective of any intervening fseek(3) or similar.

     "a+"  Open for reading and writing.  The file is created if it does not
             exist.  The stream is positioned at the end of the file.  Subse-
             quent writes to the file will always end up at the then current
             end of file, irrespective of any intervening fseek(3) or similar.

     The mode string can also include the letter "b" either as last charac-
     ter or as a character between the characters in any of the two-character
     strings described above.  This is strictly for compatibility with ISO/IEC
     9899:1990 ("ISO C90") and has no effect; the "b" is ignored.

     Finally, as an extension to the standards (and thus may not be portable),
     mode string may end with the letter "x", which insists on creating a
     new file when used with "w" or "a".  If path exists, then an error is
     returned (this is the equivalent of specifying O_EXCL with open(2)).

     Any created files will have mode "S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
     S_IROTH | S_IWOTH" (0666), as modified by the process' umask value (see
     umask(2)).

     Reads and writes may be intermixed on read/write streams in any order,
     and do not require an intermediate seek as in previous versions of stdio.
     This is not portable to other systems, however; ANSI C requires that a
     file positioning function intervene between output and input, unless an
     input operation encounters end-of-file.

     The fdopen() function associates a stream with the existing file descrip-
     tor, fildes.  The mode of the stream must be compatible with the mode of
     the file descriptor.  When the stream is closed via fclose(3), fildes is
     closed also.

     The freopen() function opens the file whose name is the string pointed to
     by filename and associates the stream pointed to by stream with it.  The
     original stream (if it exists) is closed.  The mode argument is used just
     as in the fopen() function.

     If the filename argument is NULL, freopen() attempts to re-open the file
     associated with stream with a new mode.  The new mode must be compatible
     with the mode that the stream was originally opened with:

           o   Streams originally opened with mode "r" can only be reopened
               with that same mode.

           o   Streams originally opened with mode "a" can be reopened with
               the same mode, or mode "w".

           o   Streams originally opened with mode "w' can be reopened with
               the same mode, or mode "a".

           o   Streams originally opened with mode "r+", "w+", or "a+"
               can be reopened with any mode.

     The primary use of the freopen() function is to change the file associ-
     ated with a standard text stream (stderr, stdin, or stdout).


RETURN VALUES

     Upon successful completion fopen(), fdopen(), and freopen() return a FILE
     pointer.  Otherwise, NULL is returned and the global variable errno is
     set to indicate the error.


ERRORS

     [EINVAL]           The mode argument to fopen(), fdopen(), or freopen()
                        was invalid.

     The fopen(), fdopen() and freopen() functions may also fail and set errno
     for any of the errors specified for the routine malloc(3).

     The fopen() function may also fail and set errno for any of the errors
     specified for the routine open(2).

     The fdopen() function may also fail and set errno for any of the errors
     specified for the routine fcntl(2).

     The freopen() function may also fail and set errno for any of the errors
     specified for the routines open(2), fclose(3) and fflush(3).


SEE ALSO

     open(2), fclose(3), fileno(3), fseek(3), funopen(3)


STANDARDS

     The fopen() and freopen() functions conform to ISO/IEC 9899:1990
     ("ISO C90").  The fdopen() function conforms to IEEE Std 1003.1-1988
     ("POSIX.1").

BSD                            January 26, 2003                            BSD
0
0 / 0 / 1
Регистрация: 13.07.2013
Сообщений: 14
15.07.2013, 19:12  [ТС] 17
Всем огромное С П А С И Б О прога заработала)) Тему можно закрывать!
Миниатюры
Ошибка Debug Asserition Failed Expression:(stream !=NULL)  
0
15.07.2013, 19:12
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
15.07.2013, 19:12
Помогаю со студенческими работами здесь

Debug Assertion Failed! Expression: string subscript out of range
Вот сегодня трудился целый день над игрой, и дошёл до момента когда начала появлятся выше...

При запуске выдает expression stream !=null; что делать?
задача такая: написать прогу, которая будет решать систему линейных уравнений методом гаусса....

Debug Assertion Failed! expression is_block_type valid(header-_block_use)
Как я могу исправить эту ошибку? Не понимаю, почему она возникает. Ошибка возникает при...

Ошибка file_get_contents failed to open stream: HTTP request failed
Внимание! В этом коде нет смысла и нет морали, поэтому если вы этого не ожидали читаем ниже: ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
17
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru