Home »
C programs »
C common errors programs
Here, we will learn why an error: switch quantity not an integer occurs and how to fix it in C programming language?
Submitted by IncludeHelp, on September 02, 2018
The switch statement only works with integral type of values/variables, integral types like integer, character.
The error switch quantity not an integer occurs if the value/variables passed in the switch statement is not either integer or character.
In this example, consider the statement – switch(choice) – Here, choice is a float variable i.e. we have passed a float variable in switch statement, this is the cause of error switch quantity not an integer.
Example:
#include <stdio.h> int main(void) { float choice = 2.0f; switch(choice){ case 1: printf("Case 1n"); break; case 2: printf("Case 2n"); break; case 3: printf("Case 3n"); break; case 4: printf("Case 4n"); break; default: printf("Case defaultn"); } return 0; }
Output
prog.c: In function ‘main’: prog.c:7:9: error: switch quantity not an integer switch(choice){ ^~~~~~ prog.c:5:9: warning: variable ‘choice’ set but not used [-Wunused-but-set-variable] float choice = 2.0f; ^~~~~~
How to fix?
Use only integral variables/values with the switch statement. In this example, we changed type of choice variable from float to int.
Correct code:
#include <stdio.h> int main(void) { int choice = 2; switch(choice){ case 1: printf("Case 1n"); break; case 2: printf("Case 2n"); break; case 3: printf("Case 3n"); break; case 4: printf("Case 4n"); break; default: printf("Case defaultn"); } return 0; }
Output
Case 2
C Common Errors Programs »
[c++][switch] как юзать свитч для char *?
Коротко — никак. Только для фундаментальных вроде int/char/enum можно.
- Ссылка
[c++][switch] как юзать свитч для char *?
switch(*a){
Ага, пробуем скомпилить:
#include <iostream>
using namespace std;
int main(){
const char *a = "b";
switch(*a){
case "a":
cout << "a = a" << endl; break;
case "b":
cout << "a = b" << endl; break;
}
}
Получаем ошибки:
switch.cpp:10: error: case label does not reduce to an integer constant
switch.cpp:12: error: case label does not reduce to an integer constant
★
(06.11.09 23:26:25 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
А если строки нужно сравнивать, то можно по хешам свитч делать.
- Ссылка
[c++][switch] как юзать свитч для char *?
> хешики сравнивай
Плохой совет. Хорошим может быть использование кодогенерации на темплейтах.
- Показать ответы
- Ссылка
[c++][switch] как юзать свитч для char *?
>Хорошим может быть использование кодогенерации на темплейтах
вот и займись этим
jtootf ★★★★★
(06.11.09 23:32:34 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Самое интересное, что в макроаасемблерах обычно больше можно было, и со сладким синтаксисисом.
madcore ★★★★★
(06.11.09 23:33:08 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
>> хешики сравнивай
>Плохой совет. Хорошим может быть использование кодогенерации на темплейтах.
Темплейты со стрингами не работают. Вообще, насколько я понимаю оптимально тут каким-то макаром интернить строки чтобы сравнивать их указатели.
Absurd ★★★
(06.11.09 23:33:19 MSK)
- Показать ответы
- Ссылка
Re: [c++][switch] как юзать свитч для char *?
собственно компилятор тебе все говорит правильно
- Ссылка
[c++][switch] как юзать свитч для char *?
Ладно, буду использовать нагромождения из конструкций if(), else if(). Проект не большой, просто учусь писать и использовать классы.
★
(06.11.09 23:34:59 MSK)
- Показать ответы
- Ссылка
[c++][switch] как юзать свитч для char *?
Да нет, тебе просто паскаль понравился
madcore ★★★★★
(06.11.09 23:36:27 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
void Npc::damage(int damage_type, int damage_sum){
switch(damage_type){
case 1:
cout << "Урон SMG. Одно попадание забирает 5 очков. Попаданий:" << damage_sum << endl;
health -= (5 * damage_sum);
break;
case 2:
cout << "Урон AR2. Одно попадание забирает 9 очков. Попаданий:" << damage_sum << endl;
health -= (9 * damage_sum);
break;
default:
cerr << "!!!!| Оружие не известно! Ошибка" << endl << endl;
break;
}
}
Хотел как damage_type указывать не номера, а слова, например «ar2».
★
(06.11.09 23:37:58 MSK)
- Показать ответы
- Ссылка
[c++][switch] как юзать свитч для char *?
В case ведь могут быть только константы.
- Ссылка
[c++][switch] как юзать свитч для char *?
>Хотел как damage_type указывать не номера, а слова, например «ar2».
Enum для этого и сделан
- Ссылка
[c++][switch] как юзать свитч для char *?
> Хотел как damage_type указывать не номера, а слова, например «ar2».
это неправильное желание
★★★★
(06.11.09 23:41:44 MSK)
- Показать ответы
- Ссылка
[c++][switch] как юзать свитч для char *?
Хватит быдлокодить. На самом деле в c++ switch для char не нужен.
madcore ★★★★★
(06.11.09 23:46:42 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
>это неправильное желание
Почему? ИМХО, так было бы легче юзать класс.
★
(06.11.09 23:46:48 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
switch не нужен. Юзай полиморфизм или ассоциативные контейнеры
yoghurt ★★★★★
(07.11.09 00:31:53 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
>> Хотел как damage_type указывать не номера, а слова, например «ar2».
>это неправильное желание
В Qt вроде бы по такому принципу сигналы диспатчатся.
Absurd ★★★
(07.11.09 00:35:12 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Диспатч он вообще всегда так работает. Сравниением строк…
Xellos ★★★★★
(07.11.09 00:43:10 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
Потому что это сравнение строк. Которое требует дофига операций. Когда строки будут символов под сто, а условий будет под сотню, а вызовов в секунду будет…
Xellos ★★★★★
(07.11.09 00:44:31 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
Я не понял, а что, с одинарными кавычками не прокатит?
- Показать ответ
- Ссылка
Re: [c++][switch] как юзать свитч для char *?
>Ладно, буду использовать нагромождения из конструкций if(), else if(). Проект не большой, просто учусь писать и использовать классы.
Не совсем ясна задача.
Если на входе слова из известного словаря и требуется очень быстрая обработка, то следует использовать любую библиотеку вычисления perfect hash.
Если требования по скорости более низкие или словарь заранее неизвестен, то можно использовать дерево поиска.
Если требований по скорости нет вообще — то можно использовать последовательный перебор строк. Например, можно хранить нужные слова в массиве вместе с указателеми на функцию обработки.
sign ★
(07.11.09 01:44:52 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
прочитал
тяжелый случай у 70%
нафиг так мучать С++
namezys ★★★★
(07.11.09 01:54:29 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Поясню. Как такая конструкция:
switch(a%4) {
case 0:
do_smth;
{
case 2:
do_smt2;
{
case 4:
do_smt3;
}
}
}
Имхо в этом и проблема понимая switch.
namezys ★★★★
(07.11.09 01:59:00 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Вариант: взять дистанцию левенштейна, и свитч делать уже по ней
dannie
(07.11.09 03:47:32 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
Это development
svu ★★★★★
(07.11.09 04:19:08 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
По теме. В жабке такую фичу (свитч по строкам) обещают добавить в 1.7
svu ★★★★★
(07.11.09 04:20:25 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
>Как такая конструкция
мне вот просто интересно — а что ты, собственно, хотел этой конструкцией сказать? что switch — это такой goto? что в нём можно забыть написать break? или что-то третье?
jtootf ★★★★★
(07.11.09 04:33:52 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
вот и займись этим
Заколебали. Вот идея. Именно этот код не тестировал, но рабочая 100%:
#include <boost/mpl/vector.hpp>
#include <boost/mpl/begin.hpp
#include <boost/mpl/deref.hpp>
#define ADDCASE(Name, Label, Function)
class Name
{
public:
String label_;
Name() : label_(Label){}
void execute() { Function(); return true; }
};
Потом в коде:
void function1()
{ printf("Hello from switch"); }
ADDCASE(CASEBLOCK1, "label1" , function1)
И так — сколько нужно кейсов.
Потом кладем кейсы в контейнер:
typedef boost::mpl::vector<CASEBLOCK1, CASEBLOCK2, CASEBLOCK3> CASES;
Сам свитч:
template <class Begin, class End>
struct SWITCH
{
static bool doswitch(const String& s)
{
typedef typename boost::mpl::deref<Begin>::type deref;
dereft ex;
if( ex.label_ == s )
return ex.execute();
else
return Iteratorhelper<typename boost::mpl::next<Begin>::type, End >::doswitch(s);
}
};
template <class End>
struct SWITCH<End, End>
{
static bool doswitch(const String& s)
{
bool false;
}
};
template<typename Container>
static QString PERFORMSWITCH(const String& s)
{
return SWITCH<typename boost::mpl::begin<Container>::type, typename boost::mpl::end<Container>::type>::switch(s);
}
Как пользоваться:
PERFORMSWITCH<CASES>("blabla");
Теперь компилятор сгенерит нам статическую функцию PERFORMSWITCH<CASES>, которая будет то же самое, что много if/else,
но куда проще для расширения, доработки, создания новых кейсов.
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
>которая будет то же самое
что и сравнение по хешикам, с той лишь разницей, что ты их считаешь статически (рукми объявляешь все CASEBLOCK’и). расширяемость, читаемость (как реализации так и использования), зависимости — всё на уровне плинтуса. вопорос дня: а в чём профит-то?
jtootf ★★★★★
(07.11.09 08:24:58 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
что и сравнение по хешикам
Нет, в данном случае будет вызываться оператор сравнения для строки. Можно и хэши сделать (если постараться, то и статические). В doswitch можно делать все, что хочешь.
Читаемость отличная. Профит в том, что компилятор напишет за тебя очень много кода (и сделает это оптимально), скорости, расширяемости. Сам свитч можно вынести в отдельный хидер. Тогда для написания новых свитчей тебе достаточно сделать
void function1() { printf("Hello from switch"); }
void function2() { printf("Hello from switch"); }
ADDCASE(CASEBLOCK1, "label1" , function1)
ADDCASE(CASEBLOCK2, "label2" , function1)
ADDCASE(CASEBLOCK3, "label3" , function2)
void test( )
{
...
typedef boost::mpl::vector<CASEBLOCK1, CASEBLOCK2, CASEBLOCK3> CASES2;
String mystr("label3");
PERFORMSWITCH<CASES2>(mystr);
...
}
Отличная читаемость, отличная расширяемость. И самое главное — это только идея, можно очень красиво ее доработать.
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Это как? Так?
(defgeneric switch-test (switch-case value)
(:method (x y) (equal x y))
(:method ((switch-case (eql T)) value) T))
(defmacro switch (value &rest cases)
(let ((value-var (gensym)))
(labels ((process-switch (cases)
(if (null cases)
nil
(destructuring-bind
((current-case &body body) &rest cases) cases
`(if (switch-test ,current-case ,value-var)
(progn ,@body)
,(process-switch cases))))))
`(let ((,value-var ,value))
,(process-switch cases)))))
(use-package :cl-ppcre)
(defstruct regex (pattern ".*" :type string))
(set-dispatch-macro-character
## #" (lambda (s c n)
(declare (ignore n))
(unread-char c s)
`(make-regex :pattern ,(read s t nil t))))
(defmethod switch-test ((case-of regex) (value string))
(cl-ppcre:scan (regex-pattern case-of) value))
(defun main (s)
(switch s
(#"(?i)[A-Z]" (format t "String contains letters~%"))
(#"[0-9]" (format t "String contains at least one digit and no letters~%"))
(T (format t "The value is not a string"))))
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
между вторым и третьим случаями туда неплохо бы «(#».*» (format t «String contains no letters or digits»))», но суть и так понятна, думаю
- Ссылка
[c++][switch] как юзать свитч для char *?
если один символ, то
#include <iostream>
using namespace std;
int main()
{
const char *a = "b";
switch(*a) { /* или a[0] вместо *a */
case 'a':
cout << "a = a" << endl;
break;
case 'b':
cout << "a = b" << endl;
break;
}
}
ono ★
(07.11.09 09:48:04 MSK)
- Ссылка
[c++][switch] как юзать свитч для char *?
> Отличная читаемость, отличная расширяемость.
Уййййоооооо…
kemm ★
(07.11.09 10:10:30 MSK)
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Оптимально построить finite state machine по данным строкам на этапе компиляции. Она будет небольшой, и поиск будет занимать O(N) (N — длина входной строки) или даже меньше.
- Показать ответы
- Ссылка
[c++][switch] как юзать свитч для char *?
> Уййййоооооо…
Что не так?
Вдогонку: вместо
[code]
return Iteratorhelper<typename boost::mpl::next<Begin>::type, End >::doswitch(s);
[/code]
следует читать
[code]
return SWITCH<typename boost::mpl::next<Begin>::type, End >::doswitch(s);
[/code]
- Ссылка
[c++][switch] как юзать свитч для char *?
> Оптимально построить finite state machine
Какие мы умные. Конечно можно, но делать ты это будешь приблизительно так же. Только добавится еще функция, возвращающая указатель на себя же.
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Как я понимаю, вариант в Tcl-е делает то же самое, ибо от правильных регулярных выражений производительность не пострадает.
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
В лиспе можно сделать при желании примерно так:
(case (var)
("abc[de]+f" 'first-string)
("abc[fg]" 'second-string)
(else 'third))
В С++ без препроцессора я бы не стал этого делать вообще (если только не очень жётские требования к производительности). В D можно сделать.
А говорить про твоё нагромождение капслока, что оно отлично читается — нельзя.
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Не путай интерпретацию с компиляцией, ладно?
- Показать ответ
- Ссылка
[c++][switch] как юзать свитч для char *?
Капслок здесь необязателен, препроцессор для удобства. Это вообще демонстрация идеи. И неоптимальная, за счет создания временного объекта.
- Ссылка
[c++][switch] как юзать свитч для char *?
Не смотрел реализацию тикля, но мой комментарий относился не конкретно к тиклю, и компиляции там ничего не мешает. Вообще реализация case-а по строкам с использованием FSM идеологически очень похожа на реализацию case-а с использованием таблицы переходов.
- Ссылка
[c++][switch] как юзать свитч для char *?
В полку индусов прибыло. Зачем вы за этот switch зацепились. Нагородите всяких макросов, шаблонами все обложите, и тот кто будет разбирать ваш код после вас, будет яростно писать кипятком. Чем плох такой вариант?
inline bool _IsEqu(const char* s1,const char* s2) { return (strcmp(s1,s2)==0); };
void Process(const char* text)
{
if(_IsEqu(text,"aaa"))
{
//do some ...
}
else if(_IsEqu(text,"bbb"))
{
//do some ...
}
else if(_IsEqu(text,"ccc"))
{
//do some ...
}
else
{
pAnIc();
}
}
З.Ы. Без _IsEqu можно было обойтись, но мне кажется, что так легче читается, а назначение этой функции можно понять из названия.
- Показать ответы
- Ссылка
[c++][switch] как юзать свитч для char *?
>Чем плох такой вариант?
void Process(const char* text)
{
if(_IsEqu(text,»aaa»))
{
//do some …
}
else if(_IsEqu(text,»bbb»))
{
//do some …
}
else if(_IsEqu(text,»ccc»))
{
//do some …
}
else if(_IsEqu(text,»ccc»))
{
//do some …
}
else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
}
{
//do some …
} else if(_IsEqu(text,»ccc»))
{
//do some …
}
else
{
pAnIc();
}
}
madcore ★★★★★
(07.11.09 15:24:47 MSK)
- Ссылка
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.
- Forum
- Beginners
- switch statments :switch quantity not an
switch statments :switch quantity not an integer
need some help im writing a class and the constructor for it is:
|
|
heres my main function that i used to test my class.
|
|
i was testing it out but i keep getting error «switch quantity not an integer».
does this mean i can’t use switch with string? if there any way to do this? i really don’t want to use if else statements.
You can’t. You have to use if/elses in this case.
yea i ended up doing that it worked… i didn’t want to though, its so tedious and looks ugly.
Switch on a string:
http://www.cplusplus.com/forum/general/11460/#msg54095
(Scroll down to the second half of my post)
Hope this helps.
[edit]
BTW, you could switch on the first character of the string:
|
|
Good luck!
Last edited on
Well you could create an enum in your main code (eg: enum variables{‘-‘=0,’+’=1,…}) and then just comment the enum assignments in the switch statement for readability.
@stavros, that’s a good idea. i will try that. but switch accepts enum types as its parameter?
Switch accepts anything which default-promotes to an integer value, including an enum.
You cannot name enumerated values with character literals. An enumerated value must be identifiers, just like every other value name in your program…
…Which leads back to the original problem: how to select based upon a string value? I’ve given you two answers.
To involve an enum is only useful if you plan to use them as magic values which are used in multiple places in your program. Otherwise it is overhead.
so that means is use enum to create a token type and pass the an object of type token to switch, it will work?
Well, enum types default to a number, don’t they?
did you get this resolved? if so, can you mark it as solved.
Topic archived. No new replies allowed.
Recommended Answers
See the changes
#include <stdio.h> [B]int [/B]main([B]void[/B]) { int hello;[B]//* removed[/B] printf("Hi, Enter any value > "); scanf("%d",&hello); switch (hello) { case 1: printf("your 1 luck number is > %dn",hello); case 2: printf("your 2 luck number is > %dn",hello); case 3: printf("your 3 luck number is > …
Jump to Post
The problem is with the hello variable.
When you write
int *hello; // What you're saying is create a pointer called hello. // When you write cout << hello; // hello will be some arbitrary hexadecimal number(a memory address) // When you write cout << *hello; …
Jump to Post
Hey,
I found a solution!
Simply force type-cast it as an int.
switch(int(hello))
I tried it out with gcc under Linux, like you said you had tried. It worked for me. I hope it works with your current situation. I’m sorry my last one wasn’t …
Jump to Post
All 9 Replies
SpS
34
Posting Pro
16 Years Ago
See the changes
#include <stdio.h>
[B]int [/B]main([B]void[/B])
{
int hello;[B]//* removed[/B]
printf("Hi, Enter any value > ");
scanf("%d",&hello);
switch (hello)
{
case 1: printf("your 1 luck number is > %dn",hello);
case 2: printf("your 2 luck number is > %dn",hello);
case 3: printf("your 3 luck number is > %dn",hello);
default: printf("your 4 luck number is > %dn",hello);
}
}
Are you sure you don’t want break after each case?
nanodano
0
Junior Poster in Training
16 Years Ago
The problem is with the hello variable.
When you write
int *hello;
// What you're saying is create a pointer called hello.
// When you write
cout << hello; // hello will be some arbitrary hexadecimal number(a memory address)
// When you write
cout << *hello; // *hello = the data stored at the address of hello(that hexadecimal number from before)
The problem is that you didn’t create an integer. You create a pointer to an integer.
To fix the problem, you need to remove the asterisk* in front of hello in the line
int *hello;
The reason you get a segmentation fault when you try to
switch(*hello)
is probably because the switch statement uses its parameter as an int. When it compiles/runs it takes the parameter, and it translates the variable name(in this case *hello) into an address that it can use. Somewhere between the looking up of the address that is pointed to by hello…..you are trying to use some number X as a memory location. The problem is, you don’t know WHAT X is, and more chance than not, it is a memory location that is not in the same data segment as your program, therefore you get a segmentation error.
I hope this helps.
— Dano
16 Years Ago
Thanks sunnypalsingh
Thanks Nanodano
but I need hello to be a pointer because it might be passed as an argument to some function (like in case of use ‘recv’ in socket programing) in the program.
Actually I submet a very simple program but what if the program read hello from the keyboard and send it to another side in a socket connection, ofcourse, I will need hello to be a pointer.
so the change must be somewhere in the program rather than the decleration of hello.
but where?!!
thanks again
Moloza
nanodano
0
Junior Poster in Training
16 Years Ago
Hey,
I found a solution!
Simply force type-cast it as an int.
switch(int(hello))
I tried it out with gcc under Linux, like you said you had tried. It worked for me. I hope it works with your current situation. I’m sorry my last one wasn’t helpful, I didn’t think about why it would need to be a pointer. I better keep things like that in mind!
16 Years Ago
I found a solution!
Simply force type-cast it as an int.
switch(int(hello))
That’s not a solution, that’s just hiding a problem. Solutions were already presented.
nanodano
0
Junior Poster in Training
16 Years Ago
How is that hiding a problem vs a solution? I agree that removing the * and not letting hello be a pointer is changing something. Casting hello (which is declared as an int) to an int isn’t changing anything.
What is the problem? The compiler isn’t recognizing hello as an int.
But hello IS an int. So, all you need to do is TELL the compiler: «Hey, that IS an int, use it like one.»
What would you consider a «solution» then?
Maybe try a different compiler?
16 Years Ago
How is that hiding a problem vs a solution? I agree that removing the * and not letting hello be a pointer is changing something. Casting hello (which is declared as an int) to an int isn’t changing anything.
Clue: a pointer is not an integer. Merely telling the compiler that you know that a point is an integer to keep it quiet is hiding the real problem, that the value is not being read into an integer.
nanodano
0
Junior Poster in Training
16 Years Ago
Well,
I suppose a solution to that would to declare one variable as a pointer and one as an int.
Maybe something like:
int hello;
int *hello_ptr;
hello_ptr = &hello;
This way hello really is an int, and you still have a pointer to it.
16 Years Ago
Or just do it like it was already presented.
I guess the real issue for moloza is this.
but I need hello to be a pointer because it might be passed as an argument to some function (like in case of use ‘recv’ in socket programing) in the program.
Actually I submet a very simple program but what if the program read hello from the keyboard and send it to another side in a socket connection, ofcourse, I will need hello to be a pointer.
No moloza, you don’t need a pointer. The address of your variable will become a pointer to it. Reread sunnypalsingh‘s post a couple more times. There a pointer to hello is being passed to scanf
.
BTW, the original is passing a pointer to a pointer.
int *hello;
scanf("%d",&hello);
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.