When I try to draw lines in Visual Studio 2019 with graphics.h I keep getting 2 types of errors.
This is an example I’m trying to get to work on my compiler from geeksforgeeks.org
Errors
E0167 — argument of type «const char*» is incompatible with lies 2 parameter of type «char*» — Line 17
and
C2664 — ‘void initgraph(int*,int*,char*)’; cannot convert argument 3 from ‘const char[1] to ‘char*’ — Line 17
My code:
'''// C++ Implementation for drawing line
#include <graphics.h>
// driver code
int main()
{
// gm is Graphics mode which is a computer display
// mode that generates image using pixels.
// DETECT is a macro defined in "graphics.h" header file
int gd = DETECT, gm;
// initgraph initializes the graphics system
// by loading a graphics driver from disk
initgraph(&gd, &gm, "");
// line for x1, y1, x2, y2
line(150, 150, 450, 150);
// line for x1, y1, x2, y2
line(150, 200, 450, 200);
// line for x1, y1, x2, y2
line(150, 250, 450, 250);
getch();
// closegraph function closes the graphics
// mode and deallocates all memory allocated
// by graphics system .
closegraph();
}'''
If you google «MSDN fopen_s» and read the documentation on the Microsoft Developer Network, you will find that the function prototype is not identical to fopen():
errno_t fopen_s(
FILE** pFile,
const char *filename,
const char *mode
);
This means your code in that area would change to look like:
FILE *inFile;
errno_t errcode;
errcode = fopen_s(&inFile, "prices.dot","r");
if (errcode != 0) { /* do error handling, perhaps quit */ }
Alternately, you could continue to write old-style C code, and just use «fopen()» and at the top of your file, to shut MSVC compiler up, add the following #define:
#define _CRT_SECURE_NO_WARNINGS
Note, fopen_s() was added to the C 2011 standard, and is described in section K.3.5.2.1 — meaning this is still portable C code on any modern C compiler.
Your book is probably older than 2011, and this function wasn’t part of C at that time.
- Forum
- General C++ Programming
- Error (active) E0167 argument of type «c
Error (active) E0167 argument of type «const char *» is incompatible with parameter of type «char *»
I’m getting the above error in Visual Studio 2019. I’m posting a link to two screen shots so you can see what I’m talking about. I’m happy to post code as soon as I find out what you guys need.
https://d.pr/i/flCdlY
https://d.pr/i/gVjK8R
The first screen shot is the original error. You’ll notice, however, in the second screen shot the error changed to
Error (active) E0144 a value of type «const char *» cannot be used to initialize an entity of type «char *const»
When I did Peek Definition on do_flee
Since you’re already ignoring the 2nd parameter in do_flee, you can simply do
|
|
if you were going to use it, working with string literals directly is annoying. it is a lot easier to do this:
const int smallest_allowed_size{20}; //whatever size
char mt[smallest_allowed_size] = «»;
foo(mt); //this works, you pass in a char*, not a const char* now
is there a reason you want to use C strings?
Last edited on
This game was written 10 years ago. I’m dusting it off to play it again and make it better. I’m also dusting off my rudimentary C++ knowledge so this is a learning project of sorts. Strangely, I gave this a go about 5 years ago and had it up and running in VS 2017.
salem c:
I made the change you suggested but the build still failed. If you weren’t going to use a second parameter anyway why even include it in the definition to begin with? Why was it written this way?
jonnin:
My main goal with this project it so make this code better. I’ll try to figure out a way to incorporate the changes you have suggested.
older compilers tolerated what you were doing, using char* off string literals, but stricter rules prevent it now. its probably possible to lower the compilers complaints to take it, if you have too many to fix.
if your goal is to fix it up nice, then moving to c++ <string> is the way to go. It solves a great many problems, but may be too much to take on.
Last edited on
So back to my original question. Is there a way to get this to compile in the meantime? Any suggestions on changing settings to not be so strict?
Just glancing through the errors almost all of them (like 2600) are some form of:
can’t convert from const char[*] to char *
Could you elaborate on your original post and how to implement it?
Last edited on
Is there a way to get this to compile in the meantime?
I don’t think so with VS 2019. You can disable warnings, but not errors.
Maybe some old compiler might work.
Is the source code somewhere available ?
I think the implicit const char * -> char * is configurable in MSVC.
Thomas1965
I’m sure there has to be a way to compile this in VS 2019. It is, afterall, a C++ program that has compiled on previous versions of VS. It may be a matter of settings or changing the code but I’m confident it can be done.
Here’s my email. Reach out and I’ll send you, or anyone else that’s interested, the source code
bishoposiris@gmail.com
helios
Can you elaborate? Are you using MS Visual C++ and MS Visual Studio interchangeably?
Last edited on
g++ supports it as well, by default actually. You have to tell it to be picky.
helios
I read the info on permissive standards. I changed mine to /permissive and the number of errors dropped down to 38.
Thanks everyone!
Topic archived. No new replies allowed.
Norman99 0 / 0 / 0 Регистрация: 23.05.2019 Сообщений: 26 |
||||
1 |
||||
26.10.2019, 08:15. Показов 6859. Ответов 4 Метки c/c++ (Все метки)
Всем привет, подскажите пожалуйста, в проекте MS Visual Studio 2017 напротив строчки lua_pushlstring(L, result, result_len);
0 |
530 / 179 / 38 Регистрация: 18.08.2012 Сообщений: 886 |
|
26.10.2019, 08:31 |
2 |
↓↓↓
// Finish HMAC computation and fetch result. void lua_pushlstring (lua_State *L, const char *s, size_t len);. Pushes the string pointed to by s with size len onto the stack.
0 |
0 / 0 / 0 Регистрация: 23.05.2019 Сообщений: 26 |
|
26.10.2019, 08:56 [ТС] |
3 |
void lua_pushlstring (lua_State *L, const char *s, size_t len) Да я это уже обнаружил, а как грамотно тогда передать unsigned char result[129] в lua_pushlstring?
0 |
untyped 530 / 179 / 38 Регистрация: 18.08.2012 Сообщений: 886 |
||||||||||||
26.10.2019, 11:52 |
4 |
|||||||||||
утрированный пример 1:
утрированный пример 2:
утрированный пример 3:
и самое главное… : суть:
0 |
Байт Диссидент 27497 / 17185 / 3784 Регистрация: 24.12.2010 Сообщений: 38,714 |
||||
27.10.2019, 08:48 |
5 |
|||
Norman99, попробуйте явно привести тип
0 |
#c #c #visual-c
#c #c #visual-c
Вопрос:
я очень новичок в C, и, работая над примерами в книге, я продолжаю получать ошибку «C аргумент типа * несовместим с параметром типа **». Я использую Visual studio 2019 C . Вот где я получаю сообщение об ошибке при использовании fopen_s:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *inFile;
inFile = fopen_s("prices.dot","r"); /*Here is the line with an error*/
if (inFile == NULL)
{
printf("nThis file does not existL");
printf("nPlease make sure that this file currently exist");
exit(1);
}
printf("nThe file has been succfully open for reading.");
return(0);
}
когда я использую «fopen», я получаю предупреждение, в котором мне предлагается использовать fopen_s, а когда я использую fopen_s, я получаю другую ошибку. Мне было интересно, могу ли я получить какую-либо помощь в решении этого вопроса. Спасибо!
Комментарии:
1. Вы используете C или C ? Весь этот код выглядит как C.
2.
fopen_s
имеет подпись, отличнуюfopen
от .3. Аргументы to
fopen_s
не совпадают сfopen
. См . docs.microsoft.com/en-us/cpp/c-runtime-library/reference /…4. Я предлагаю вам отключить предупреждения, которые говорят вам использовать
_s
версии функций. Все они зависят от Microsoft, поэтому ваш код больше не переносим.5.
auto res = fopen_s(amp;inFile, "prices.dot","r")
.
Ответ №1:
Если вы загуглите «MSDN fopen_s» и прочтете документацию в сети разработчиков Microsoft, вы обнаружите, что прототип функции не идентичен fopen():
errno_t fopen_s(
FILE** pFile,
const char *filename,
const char *mode
);
Это означает, что ваш код в этой области изменится, чтобы выглядеть следующим образом:
FILE *inFile;
errno_t errcode;
errcode = fopen_s(amp;inFile, "prices.dot","r");
if (errcode != 0) { /* do error handling, perhaps quit */ }
С другой стороны, вы можете продолжать писать код на C в старом стиле и просто использовать «fopen ()», а в верхней части вашего файла, чтобы закрыть компилятор MSVC, добавьте следующий #define:
#define _CRT_SECURE_NO_WARNINGS
Обратите внимание, что функция fopen_s() была добавлена в стандарт C 2011 и описана в разделе K.3.5.2.1 — это означает, что это все еще переносимый код C на любом современном компиляторе C.
Ваша книга, вероятно, старше 2011 года, и в то время эта функция не была частью C.
Комментарии:
1. Спасибо всем вам за ответы и предложения. Да, я использую C. Я отключил предупреждение, используя #define _CRT_SECURE_NO_WARNINGS . Это сработало.