Error c2100 illegal indirection

I have a very simple program written to define a * operator in an array template class. When I try to compile it gives me an error "illegal indirection". Any help on the matter would be greatly

I have a very simple program written to define a * operator in an array template class.
When I try to compile it gives me an error «illegal indirection».
Any help on the matter would be greatly appreciated!

This is the operator definition:

template <typename T>                                                                   
NumericArray<T> NumericArray<T>::operator * (const int factor) const
{
NumericArray<T>* TempArray2 = new NumericArray<T>(Size());
for (int i=0; i<Size(); i++)
{
    *TempArray2[i] = ((GetElement(i))*(factor));
}
return *TempArray2;
}

And this is the implementation in the test main function:

cout<<((*intArray1)*5).GetElement(0);                                   
cout<<((*intArray1)*5).GetElement(1);
cout<<((*intArray1)*5).GetElement(2);

Any ideas?

asked Apr 22, 2013 at 12:32

Byron's user avatar

Don’t forget your operator precedence rules. It seems that you want:

(*TempArray2)[i]

Otherwise your expression *TempArray2[i] is considered as *(TempArray2[i]) and I suppose your NumericArray<T> type doesn’t have the unary * operator overloaded.

answered Apr 22, 2013 at 12:34

Joseph Mansfield's user avatar

Joseph MansfieldJoseph Mansfield

107k19 gold badges239 silver badges322 bronze badges

In *TempArray2[i], the * is applied to TempArray[2] because of the precedence rules, and there’s a fair chance that the array elements don’t have a unary * operator.

But your use of dynamic allocation and then dereferencing to return by value means that you have a memory leak.
(You don’t need new to create objects in C++ — you probably don’t need to use it in main either.)

This would be better (and avoids the whole indirection issue):

template <typename T>                                                                   
NumericArray<T> NumericArray<T>::operator * (int factor) const
{
    NumericArray<T> TempArray(Size());
    for (int i = 0; i < Size(); i++)
    {
        TempArray[i] = GetElement(i) * factor;
    }
    return TempArray;
}

answered Apr 22, 2013 at 13:06

molbdnilo's user avatar

molbdnilomolbdnilo

63.2k3 gold badges41 silver badges78 bronze badges

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler errors C2100 through C2199

Compiler errors C2100 through C2199

04/21/2019

C2119

C2123

C2125

C2126

C2127

C2136

C2176

C2187

C2189

C2119

C2123

C2125

C2126

C2127

C2131

C2136

C2176

C2187

C2189

1ccab076-0954-4386-b959-d3112a6793ae

Compiler errors C2100 through C2199

The articles in this section of the documentation explain a subset of the error messages that are generated by the compiler.

[!INCLUDEerror-boilerplate]

Error messages

Error Message
Compiler error C2100 illegal indirection
Compiler error C2101 ‘&’ on constant
Compiler error C2102 ‘&’ requires l-value
Compiler error C2103 ‘&’ on register variable
Compiler error C2104 ‘&’ on bit field ignored
Compiler error C2105 operator‘ needs l-value
Compiler error C2106 operator‘: left operand must be l-value
Compiler error C2107 illegal index, indirection not allowed
Compiler error C2108 subscript is not of integral type
Compiler error C2109 subscript requires array or pointer type
Compiler error C2110 ‘+’: cannot add two pointers
Compiler error C2111 ‘+’: pointer addition requires integral operand
Compiler error C2112 ‘-‘: pointer subtraction requires integral or pointer operand
Compiler error C2113 ‘-‘: pointer can only be subtracted from another pointer
Compiler error C2114 operator‘: pointer on left; needs integral value on right
Compiler error C2115 operator‘: incompatible types
Compiler error C2116 function parameter lists differed
Compiler error C2117 identifier‘: array bounds overflow
Compiler error C2118 negative subscript
Compiler error C2119 identifier‘: the type for ‘type‘ cannot be deduced from an empty initializer
Compiler error C2120 ‘void’ illegal with all types
Compiler error C2121 ‘#’: invalid character: possibly the result of a macro expansion
Compiler error C2122 identifier‘: prototype parameter in name list illegal
Compiler error C2123 identifier‘: alias templates cannot be explicitly or partially specialized
Compiler error C2124 divide or mod by zero
Compiler error C2125 ‘constexpr’ is incompatible with ‘token
Compiler error C2126 identifier‘ cannot be declared with ‘constexpr’ specifier
Compiler error C2127 identifier‘: illegal initialization of ‘constexpr’ entity with a non-constant expression
Compiler error C2128 function‘: alloc_text/same_seg applicable only to functions with C linkage
Compiler error C2129 static function ‘identifier‘ declared but not defined
Compiler error C2130 #line expected a string containing the filename, found ‘token
Compiler error C2131 expression did not evaluate to a constant
Compiler error C2132 syntax error: unexpected identifier
Compiler error C2133 identifier‘: unknown size
Compiler error C2134 function‘: call does not result in a constant expression
Compiler error C2135 operator‘: illegal bit field operation
Compiler error C2136 authoring API contract not allowed
Compiler error C2137 empty character constant
Compiler error C2138 illegal to define an enumeration without any members
Compiler error C2139 class‘: an undefined class is not allowed as an argument to compiler intrinsic type trait ‘trait
Compiler error C2140 type‘: a type that is dependent on a generic type parameter is not allowed as an argument to compiler intrinsic type trait ‘trait
Compiler error C2141 array size overflow
Compiler error C2142 function declarations differ, variable parameters specified only in one of them
Compiler error C2143 syntax error: missing ‘token1‘ before ‘token2
Compiler error C2144 syntax error: ‘type‘ should be preceded by ‘token2
Compiler error C2145 syntax error: missing ‘token‘ before identifier
Compiler error C2146 syntax error: missing ‘token‘ before identifier ‘identifier
Compiler error C2147 syntax error: ‘token‘ is a new keyword
Compiler error C2148 total size of array must not exceed 0xvalue bytes
Compiler error C2149 identifier‘: named bit field cannot have zero width
Compiler error C2150 identifier‘: bit field must have type ‘int’, ‘signed int’, or ‘unsigned int’
Compiler error C2151 more than one language attribute
Compiler error C2152 identifier‘: pointers to functions with different attributes
Compiler error C2153 integer literals must have at least one digit
Compiler error C2154 type‘: only enumeration type is allowed as an argument to compiler intrinsic type trait ‘trait
Compiler error C2155 ‘?’: invalid left operand, expected arithmetic or pointer type
Compiler error C2156 pragma must be outside function
Compiler error C2157 identifier‘: must be declared before use in pragma list
Compiler error C2158 type‘: #pragma make_public directive is currently supported for native non-template types only
Compiler error C2159 more than one storage class specified
Compiler error C2160 ‘##’ cannot occur at the beginning of a macro definition
Compiler error C2161 ‘##’ cannot occur at the end of a macro definition
Compiler error C2162 expected macro formal parameter
Compiler error C2163 function‘: not available as an intrinsic function
Compiler error C2164 function‘: intrinsic function not declared
Compiler error C2165 modifier‘: cannot modify pointers to data
Compiler error C2166 l-value specifies const object
Compiler error C2167 function‘: too many actual parameters for intrinsic function
Compiler error C2168 function‘: too few actual parameters for intrinsic function
Compiler error C2169 function‘: intrinsic function, cannot be defined
Compiler error C2170 identifier‘: not declared as a function, cannot be intrinsic
Compiler error C2171 operator‘: illegal on operands of type ‘type
Compiler error C2172 function‘: actual parameter is not a pointer: parameter number
Compiler error C2173 function‘: actual parameter is not a pointer: parameter number, parameter list number
Compiler error C2174 function‘: actual parameter has type ‘void’: parameter number, parameter list number
Compiler error C2175 locale‘: invalid locale
Compiler error C2176 a return statement cannot appear in the handler of a function-try-block associated with a constructor
Compiler error C2177 constant too big
Compiler error C2178 identifier‘ cannot be declared with ‘specifier‘ specifier
Compiler error C2179 type‘: an attribute argument cannot use type parameters
Compiler error C2180 controlling expression has type ‘type
Compiler error C2181 illegal else without matching if
Compiler error C2182 identifier‘: illegal use of type ‘void’
Compiler error C2183 syntax error: translation unit is empty
Compiler error C2184 type‘: illegal type for __except expression
Compiler error C2185 identifier‘: illegal based allocation
Compiler error C2186 operator‘: illegal operand of type ‘void’
Compiler error C2187 syntax error: ‘token‘ was unexpected here
Compiler error C2188 number‘: too big for wide character
Compiler error C2189 ‘alignas’ attribute cannot be applied to a bit-field, a function parameter, an exception declaration, or a variable declared with ‘register’ storage class
Compiler error C2190 first parameter list longer than second
Compiler error C2191 second parameter list longer than first
Compiler error C2192 parameter ‘number‘ declaration different
Compiler error C2193 identifier‘: already in a segment
Compiler error C2194 identifier‘: is a text segment
Compiler error C2195 identifier‘: is a data segment
Compiler error C2196 case value ‘value‘ already used
Compiler error C2197 function‘: too many arguments for call
Compiler error C2198 function‘: too few arguments for call
Compiler error C2199 syntax error: found ‘identifier (‘ at global scope (was a declaration intended?)

See also

C/C++ Compiler and build tools errors and warnings
Compiler errors C2000 — C3999, C7000 — C7999

Содержание

  1. Compiler errors C2100 through C2199
  2. Error c2100 illegal indirection
  3. Illegal indirection #467
  4. Comments
  5. Footer
  6. Error c2100 illegal indirection
  7. Error c2100 illegal indirection

Compiler errors C2100 through C2199

The articles in this section of the documentation explain a subset of the error messages that are generated by the compiler.

The Visual Studio compilers and build tools can report many kinds of errors and warnings. After an error or warning is found, the build tools may make assumptions about code intent and attempt to continue, so that more issues can be reported at the same time. If the tools make the wrong assumption, later errors or warnings may not apply to your project. When you correct issues in your project, always start with the first error or warning that’s reported, and rebuild often. One fix may make many subsequent errors go away.

To get help on a particular diagnostic message in Visual Studio, select it in the Output window and press the F1 key. Visual Studio opens the documentation page for that error, if one exists. You can also use the search tool at the top of the page to find articles about specific errors or warnings. Or, browse the list of errors and warnings by tool and type in the table of contents on this page.

Not every Visual Studio error or warning is documented. In many cases, the diagnostic message provides all of the information that’s available. If you landed on this page when you used F1 and you think the error or warning message needs additional explanation, let us know. You can use the feedback buttons on this page to raise a documentation issue on GitHub. If you think the error or warning is wrong, or you’ve found another problem with the toolset, report a product issue on the Developer Community site. You can also send feedback and enter bugs within the IDE. In Visual Studio, go to the menu bar and choose Help > Send Feedback > Report a Problem, or submit a suggestion by using Help > Send Feedback > Send a Suggestion.

You may find additional assistance for errors and warnings in Microsoft Learn Q&A forums. Or, search for the error or warning number on the Visual Studio C++ Developer Community site. You can also search Stack Overflow to find solutions.

For links to additional help and community resources, see Visual C++ Help and Community.

Источник

Error c2100 illegal indirection

I have to create a program which has 3 functions, one to create and fill an array at random, one to print it on the screen, and one to sort it. Im only having about 2 errors that I cant seem to know how to fix Error 2 error C2100: illegal indirection c:userspcdesktopusbanthonydocumentsvisual studio 2012projectsfinalllfinalllfinalll.cpp 55
and related to it Error 3 error C2106: ‘=’ : left operand must be l-value c:userspcdesktopusbanthonydocumentsvisual studio 2012projectsfinalllfinalllfinalll.cpp 55
and 4 IntelliSense: operand of ‘*’ must be a pointer c:UserspcDesktopUSBAnthonyDocumentsVisual Studio 2012ProjectsFinalllFinalllFinalll.cpp 55
.

Im pretty sure that the sorting technique is correct as its the same as the one in my course, but Im not too sure about the usage of the pointers.

Sorry if my english is not too good, it’s not my main language
Thank you

Your prototypes don’t match your definitions:

they do not refer to the same function.

About the error
*(*(ArrayPtr +i)+j)=rand()%56+2;
`ArrayPtr’ is a pointer to an int, so `ArrayPtr[i]’ is an int
It does not make sense to say `42[13]’

Have your definitions match your prototype:

Источник

Illegal indirection #467

I’m trying to use it in VS2015 but when I try to compile I got this error.

C2100 Illegal indirection

The text was updated successfully, but these errors were encountered:

This is strange, because the project compiles with AppVeyor without problems:

What is the exact error message? What compilation flags are you using?

I just updated my VS2015 and its working fine.
Thanks!

I have this issue too. Using 2.1.1.

Microsoft Visual Studio Community 2015
Version 14.0.24720.00 Update 1

All I have done is added #include «json.hpp» to my source file.

c:pathtojson.hpp(887): error C2100: illegal indirection
c:pathtojson.hpp(898): note: see reference to class template instantiation ‘nlohmann::detail::static_constnlohmann::detail::to_json_fn’ being compiled

Compilation flags generated by CMake:
/Yu»StdAfx.h» /GS /TP /W3 /Zc:wchar_t /I»C:Boostincludeboost-1_60″ /Zi /Gm- /Od /Ob0 /Fd»MyLib.dirDebugMyLib.pdb» /Zc:inline /fp:precise /D «WIN32» /D «_WINDOWS» /D «_DEBUG» /D «BOOST_LOG_DYN_LINK» /D «BOOST_USE_WINAPI_VERSION=0x0601» /D «CMAKE_INTDIR=»Debug»» /D «_MBCS» /errorReport:prompt /WX- /Zc:forScope /RTC1 /GR /Gd /MDd /Fa»Debug/» /EHsc /nologo /Fo»MyLib.dirDebug» /Fp»MyLib.dirDebugMyLib.pch»

@glennra The tests at AppVeyor work with MSVC 14.0.25420.1 (see https://ci.appveyor.com/project/nlohmann/json for detailed output). I’m not sure about the differences to the version you are using, but @brunohkbx seems to have fixed the issue by updating.

Thanks. It works with:
Microsoft Visual Studio Community 2015
Version 14.0.25431.01 Update 3

VS usually automatically offers updates but in this case it had not done that so I had to manually download and run the updater.

I can confirm this, by updating from Update 1 to Update 3 everything works fine.

Thanks for reporting!

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Error c2100 illegal indirection

2c++ learner
ну во первых, нафига приводить к char *, если твоя переменная и так такого типа
во вторых,

что то разыменовал и обращаешься как к указателю? изначально у тебя что было? указатель на указатель? или обычный указатель? или объект на стеке и перегруженный оператор ->

так или иначе, должно быть либо f-> (если f указатель либо объект на стеке с перегруженной операцией ->), либю (*f)-> (если f — указатель на указатель), либо (*f). (если f — обычный указатель).

Какой компилятор? может компилятор глючит?

I invented the term Object-Oriented, and I can tell you I did not have C++ in mind. (c)Alan Kay

My other car is cdr.

Q: Whats the object-oriented way to become wealthy?
A: Inheritance

2pproger
Спасибо, бревна не заметил))
Действительно и нафига?)) Проблема была не в первой переменной и ее приведением, а с *fs-> – накосячил я, жесточайшим образом тут, каюсь )))
Прога теперь компилоцо!)) …но есть теперь другая проблема я не вижу файла, который она должна создать(( , она же его должна создать в Дебаг папке хотя бы нет?

Компилилка: ms vc — — 2003й.

По-моему тот все норм нет?

Может еще какой ios::$$ задасть, м? чеб файл создавала?

Подебажил код кнопками f10/f11 в коде fstream в надежде отыскать причину по которой fstream отказывается создать файл с записью … выяснилось что он в своей основе используют fopen/fclose/fwrite/fread… перешел на них. Теперь файл создается!

Источник

Error c2100 illegal indirection

2c++ learner
ну во первых, нафига приводить к char *, если твоя переменная и так такого типа
во вторых,

что то разыменовал и обращаешься как к указателю? изначально у тебя что было? указатель на указатель? или обычный указатель? или объект на стеке и перегруженный оператор ->

так или иначе, должно быть либо f-> (если f указатель либо объект на стеке с перегруженной операцией ->), либю (*f)-> (если f — указатель на указатель), либо (*f). (если f — обычный указатель).

Какой компилятор? может компилятор глючит?

I invented the term Object-Oriented, and I can tell you I did not have C++ in mind. (c)Alan Kay

My other car is cdr.

Q: Whats the object-oriented way to become wealthy?
A: Inheritance

2pproger
Спасибо, бревна не заметил))
Действительно и нафига?)) Проблема была не в первой переменной и ее приведением, а с *fs-> – накосячил я, жесточайшим образом тут, каюсь )))
Прога теперь компилоцо!)) …но есть теперь другая проблема я не вижу файла, который она должна создать(( , она же его должна создать в Дебаг папке хотя бы нет?

Компилилка: ms vc — — 2003й.

По-моему тот все норм нет?

Может еще какой ios::$$ задасть, м? чеб файл создавала?

Подебажил код кнопками f10/f11 в коде fstream в надежде отыскать причину по которой fstream отказывается создать файл с записью … выяснилось что он в своей основе используют fopen/fclose/fwrite/fread… перешел на них. Теперь файл создается!

Источник

  • Remove From My Forums
  • Question

  • Hi

    I am migrating my application from vc++6.0 to vc++2013

    I am giving part of my code were the error occured

    I am also getting one more error in the same line:

    error C2440: ‘initializing’ : cannot convert from ‘int’ to ‘CBalancingPeriod &’ 

    ==================CODE=================

    if (CBalancingPeriod::Includes(m_iAccountingPeriodNo, dCurrent, dReference))
      {
       // Search the reference from the list
       for (int it = m_periods.begin(); it != m_periods.end(); it++) //vs6.0 to vs2013
       {
        CBalancingPeriod &p = *it; //error line
        if (CBalancingPeriod::Includes(m_iAccountingPeriodNo, p.m_dAccountPeriodStart, dReference))
        {
         return (&p);
        }
       }
      }

    ================CODE==========================

    Can anyone help me get through this

    thanks

Answers

  • This a not a compatibility issue of VC versions. *it is attempting to dereference an integer, which is illegal for all versions. It looks like
    it is supposed to be an iterator not an integer. 

    • Marked as answer by

      Wednesday, January 29, 2014 8:25 AM

See more:

class students
{
	char *stud_name;
	int rollno;
public:
	void set_values(char *n,int y)
	{
		stud_name=n;
		rollno=y;
	}
};
int main()
{
	char *name;
	int roll;
	int a;
	cout<<"enter the number of students";
	cin>>a;
	students *ptr=new students[a];
	for(int i=0;i<10;i++)
	{
		cout<<"enter the name and rollno of "<<i<<"th student";
		cin.get(name,20);
		cin>>roll;
		*(ptr+i)->set_values(name,roll);//here is the error
	}
        return 0;
}

Updated 27-Jun-13 11:13am

Comments


Solution 2

You’re dereferencing a pointer, then trying to use it as a pointer.

*(ptr+i)->set_values(name,roll);//here is the error

Change to…

(ptr+i)->set_values(name,roll);

Comments

Solution 1

Your code doesn’t give enough information to be able to say exactly where the problem is, but C2100 is saying that you are using a non-pointer as a pointer. With the code segment you provide here there are several possibilities.

Microsoft’s explanation can be found here[^].

Comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

  • Forum
  • General C++ Programming
  • Error C2100: Illegal Indirection

Error C2100: Illegal Indirection

After a lot of research I found out some things that I would like to verify and use in my homework. When passing a 2D array to a function as pointer, it is treated as a 1D, so hypothetically on the same line, is that right to say?
So if I want to find the address of a cell (int) I just add +4n?
And now for my homework:

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
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>

using namespace std;
const int AS = 6;
void FillingRandomly(int (*)[AS]);
void printing(int (*)[AS]);


int c;

int main()

{
	int funny = 0;
	int timpa = 0;
	int counter = 0;
	int Array[AS][AS];
	srand(time(0));


	FillingRandomly(Array);	
	

	cout << "The unsorted array is" << endl << endl;

	printing(Array);

	cout << "The sorted array is" << endl << endl;

	printing(Array);

	

		

	
	
	system("PAUSE");


	return 0;

}

void FillingRandomly(int *ArrayPtr)
{for(int i=0;i<AS;i++)
{for (int j=0;j<AS;j++)
{
*(*(ArrayPtr +i)+j)=rand()%56+2;
}
		}
}

void printing(int *Array)
{
	for(int i=0;i<AS;i++)
	{for (int j=0;j<AS*AS;j++)
	{int counter = 0;

	cout<<((Array[i] +j))<<setw(5);

			if ((Array[i] +j)%AS == 0)
				cout << endl << endl;
	}	
}
}

void forsorting(int *Brray, int funny)
{
	int dice = 0;
	int super = 0;
	int space=0;
	

	//Sorting Array[][] which is treated like Array[]

{

 for (int pass = 0; pass < AS - 1; pass++) {
        
         for (int k = 0; k < AS - 1; k++) {
            int temp;
            
                if(*(Brray+k)==*(Brray+k+1))
{
    temp=*(Brray+k);
    *(Brray+k)=*(Brray+k+1);
    *(Brray+k+1)=temp;
}
    } 

 }
}
}

I have to create a program which has 3 functions, one to create and fill an array at random, one to print it on the screen, and one to sort it. Im only having about 2 errors that I cant seem to know how to fix Error 2 error C2100: illegal indirection c:userspcdesktopusbanthonydocumentsvisual studio 2012projectsfinalllfinalllfinalll.cpp 55
and related to it Error 3 error C2106: ‘=’ : left operand must be l-value c:userspcdesktopusbanthonydocumentsvisual studio 2012projectsfinalllfinalllfinalll.cpp 55
and 4 IntelliSense: operand of ‘*’ must be a pointer c:UserspcDesktopUSBAnthonyDocumentsVisual Studio 2012ProjectsFinalllFinalllFinalll.cpp 55
.

Im pretty sure that the sorting technique is correct as its the same as the one in my course, but Im not too sure about the usage of the pointers.

Sorry if my english is not too good, it’s not my main language
Thank you

Your prototypes don’t match your definitions:

1
2
3
4
5
6
7
void FillingRandomly(int (*)[AS]);   // lines 11-12... these are correct
void printing(int (*)[AS]);


void FillingRandomly(int *ArrayPtr)  // line 51 .. this doesn't match -- it's wrong

void printing(int *Array) // line 60 .. also doesn't match 

1
2
void FillingRandomly(int (*)[AS]); //declaration line 11
void FillingRandomly(int *ArrayPtr) //definition line 51 

they do not refer to the same function.

About the error
*(*(ArrayPtr +i)+j)=rand()%56+2;
`ArrayPtr’ is a pointer to an int, so `ArrayPtr[i]’ is an int
It does not make sense to say `42[13]’

Any idea how to fix this?

Have your definitions match your prototype:

1
2
3
4
5
6
7
8
9
10
11
12
13
// These are your prototypes.  They are correct
void FillingRandomly(int (*)[AS]);
void printing(int (*)[AS]);


// These are your definitions, they are wrong
void FillingRandomly(int *ArrayPtr)
void printing(int *Array)


// change them to match your prototypes:
void FillingRandomly( int (*ArrayPtr)[AS] )
void printing( int (*Array)[AS] )

Topic archived. No new replies allowed.

randomer

0 / 0 / 0

Регистрация: 19.02.2014

Сообщений: 9

1

02.10.2014, 16:33. Показов 1954. Ответов 6

Метки нет (Все метки)


Просьба помочь с пониманием указателей в функциях.
Переползаю с delphi, поэтому просьба сильно не пинать.
Есть большая программа, пытаюсь написать отдельный модуль,
он получает данные из основной программы,
обрабатывает «кусками» и выдаёт обратно результат.

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int  c_dec(const void *input, int inputSizeBytes, void *output, 
        int *outputSizeBytes)
{   
    const guint8 *dataIn = (const guint8 *)input; //типизируем входные данные?
    guint16 *dataOut = (guint16 *)output; //типизируем выходные данные?
    short           synth[80];              
....
    for (fr_num=0; fr_num<FramePerInput; fr_num++){
        //работает функция с блоком данных, выводит в synth
        for (j=0; j<80; j++){
            *dataOut[j+(fr_num)*80]=synth[j]; //Передаём "кусок" данных на выход 
        }
    }
    *outputSizeBytes=FramePerInput*(80*(sizeof (short))); // сообщаем количество данных на выходе
....
}

При моём текущем понимании указателей, правильная «конструкция»:

C
1
*dataOut[j+(fr_num)*80]=synth[j];

Но не пропускает nmake: «error C2100: недопустимое косвенное обращение»
Если пишу

C
1
dataOut[j+(fr_num)*80]=synth[j];

компилируется, но программа «падает»
Так-же и с «*outputSizeBytes»…

Добавлено через 7 минут
Забыл добавить: основная программа сменила версию, и в новой уже не работает.
В предыдущей версии работало с разименованными переменными.
Т.е. дело в том как вызывается функция, с какими параметрами?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт Java

4015 / 2617 / 475

Регистрация: 28.04.2012

Сообщений: 8,422

02.10.2014, 17:42

2

Цитата
Сообщение от randomer
Посмотреть сообщение

правильная «конструкция»

Это по каким правилам она правильная?

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

Цитата
Сообщение от randomer
Посмотреть сообщение

Если пишу … компилируется, но программа «падает»

А где проверка выхода за границу массива output?



0



0 / 0 / 0

Регистрация: 19.02.2014

Сообщений: 9

02.10.2014, 18:04

 [ТС]

3

Цитата
Сообщение от korvin_
Посмотреть сообщение

Это по каким правилам она правильная?

При моём текущем понимании указателей :-)
Чувствую — неправильное.
Смущает то, что модуль писал по образу и подобию работающего, там именно так работает.

Цитата
Сообщение от korvin_
Посмотреть сообщение

А где проверка выхода за границу массива output?

Не делал, потому что без этого работало в предыдущей версии основной программы…



0



153 / 148 / 66

Регистрация: 20.02.2014

Сообщений: 556

02.10.2014, 19:17

4

randomer, а что передается в output при вызове функции?



0



Модератор

Эксперт PythonЭксперт JavaЭксперт CЭксперт С++

11659 / 7172 / 1704

Регистрация: 25.07.2009

Сообщений: 13,142

02.10.2014, 20:26

5

Цитата
Сообщение от randomer
Посмотреть сообщение

там именно так работает

Значит нужно смотреть, как в предыдущей версии устанавливалась переменная

Цитата
Сообщение от randomer
Посмотреть сообщение

FramePerInput

и как задавался размер строки массива

Цитата
Сообщение от randomer
Посмотреть сообщение

dataOut

и искать отличия.
Кстати, выражение

Цитата
Сообщение от randomer
Посмотреть сообщение

j+(fr_num)*80

в качестве индекса внутри строки двумерного массива выглядит более, чем подозрительно. Такое чувство, что если убрать это +(fr_num)*80 то всё заработает…



0



randomer

0 / 0 / 0

Регистрация: 19.02.2014

Сообщений: 9

03.10.2014, 10:51

 [ТС]

6

Основная программа — wireshark.
Модуль — это декодер голоса из G.729, выдаёт декодированный голос.
Данные на входе — захваченный пакет с данными.
Он дробится на кадры, их количество описывает FramePerInput = inputSizeBytes/10;
Декодируется покадрово, декодированный кадр записывается в dataOut, размер декодированного кадра так-же известен = 80.
Т.е. конструкция

C
1
j+(fr_num)*80

вполне нормальная.
Писал модуль на основе аналогичного для G.711, который идёт в «поставке» с исходниками программы, там работали с данными не разименовывая, например:

C
1
*outputSizeBytes = inputSizeBytes * 2;

что и внесло сумятицу в голову.
Получается при вызове функции передаются данные не таким способом теперь (не в том виде — не адресом в памяти)?
Ибо в предыдущей версии модуль работал…



0



0 / 0 / 0

Регистрация: 19.02.2014

Сообщений: 9

08.10.2014, 11:16

 [ТС]

7

Доброго всем времени суток.
Заработало: действительно надо было смотреть как вызывается функция…
Функция декодирования вызывается 2 раза, первый раз она должна вернуть исключительно будущий размер декодированных данных.
Чтобы при повторном вызове дали место нужного размера под запись этих данных.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

08.10.2014, 11:16

Помогаю со студенческими работами здесь

Вывести указатель — куча ошибок (недопустимое косвенное обращение, …)
Простите, туплю жестоко. Два месяца не трогал студию, забыл все конкретно.

int peremennaya=5461;…

Ошибка «Access denied» error 5 при вызове VirtualQueryEx
Всем привет. Не могу понять в чём проблема, запускаю программу от имени администратора, но данные…

«Недопустимое использование этого типа в качестве выражения»
Вот, у меня есть код (просто создаёт пустое окно без ничего), который без проблем собирается и…

Недопустимое использование оператора «PRINT», оказывающего побочное действие, в функции
Функция должна считать факториал, но выводит ошибку:
Сообщение 443, уровень 16, состояние 14,…

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

Или воспользуйтесь поиском по форуму:

7

Понравилась статья? Поделить с друзьями:
  • Error c2099 инициализатор не является константой
  • Error c2088 недопустимо для class
  • Error c2088 illegal for class
  • Error c2086 переопределение
  • Error c2086 redefinition