Except when it is the operand of the sizeof
or unary &
operator, or is a string literal being used to initialize another array in a declaration, an expression of type «N-element array of T
» is converted («decays») to an expression of type «pointer to T
«, and the value of the expression is the address of the first element of the array.
If the declaration of the array being passed is
int S[4][4] = {...};
then when you write
rotateArr( S );
the expression S
has type «4-element array of 4-element array of int
«; since S
is not the operand of the sizeof
or unary &
operators, it will be converted to an expression of type «pointer to 4-element array of int
«, or int (*)[4]
, and this pointer value is what actually gets passed to rotateArr
. So your function prototype needs to be one of the following:
T rotateArr( int (*arr)[4] )
or
T rotateArr( int arr[][4] )
or even
T rotateArr( int arr[4][4] )
In the context of a function parameter list, declarations of the form T a[N]
and T a[]
are interpreted as T *a
; all three declare a
as a pointer to T
.
You’re probably wondering why I changed the return type from int
to T
. As written, you’re trying to return a value of type «4-element array of 4-element array of int
«; unfortunately, you can’t do that. C functions cannot return array types, nor can you assign array types. IOW, you can’t write something like:
int a[N], b[N];
...
b = a; // not allowed
a = f(); // not allowed either
Functions can return pointers to arrays, but that’s not what you want here. D
will cease to exist once the function returns, so any pointer you return will be invalid.
If you want to assign the results of the rotated array to a different array, then you’ll have to pass the target array as a parameter to the function:
void rotateArr( int (*dst)[4], int (*src)[4] )
{
...
dst[i][n] = src[n][M - i + 1];
...
}
And call it as
int S[4][4] = {...};
int D[4][4];
rotateArr( D, S );
This guide provides step-by-step instructions for resolving the «subscripted value is neither array nor pointer» error in C and C++ programming languages. This error occurs when the compiler encounters an attempt to access an array or pointer element using the subscript operator []
, but the variable being accessed is not an array or pointer.
Table of Contents
- Understanding the Error
- Step-by-Step Solution
- FAQs
- Related Links
Understanding the Error
The «subscripted value is neither array nor pointer» error is a type of compile-time error. It occurs when the programmer tries to use the subscript operator []
with a variable that is not an array or pointer.
Examples of incorrect usage that can cause this error:
int main() {
int number;
number[0] = 5; // Error: subscripted value is neither array nor pointer
return 0;
}
int main() {
int number = 42;
int value = number[0]; // Error: subscripted value is neither array nor pointer
return 0;
}
Step-by-Step Solution
To resolve the «subscripted value is neither array nor pointer» error, follow these steps:
Identify the problematic variable: Locate the line of code where the error occurs, and identify the variable causing the issue.
Check the variable declaration: Ensure that the variable is declared as an array or pointer. If not, either change the variable type or update the code to use the correct data structure.
Fix the variable usage: Update the code to access elements of the array or pointer correctly, using the subscript operator []
.
Here are examples of how to fix the error:
Example 1: Using an Array
int main() {
int numbers[5]; // Declare an array of integers
numbers[0] = 5; // Correct usage of the subscript operator
return 0;
}
Example 2: Using a Pointer
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers = (int *)malloc(5 * sizeof(int)); // Allocate memory for an array of integers
if (numbers == NULL) {
fprintf(stderr, "Memory allocation failedn");
return 1;
}
numbers[0] = 5; // Correct usage of the subscript operator
free(numbers);
return 0;
}
FAQs
1.
What causes the «subscripted value is neither array nor pointer» error?
This error occurs when the programmer tries to use the subscript operator []
with a variable that is not an array or pointer.
2.
How do I fix the «subscripted value is neither array nor pointer» error?
To fix this error, ensure that the variable causing the issue is declared as an array or pointer and that you are using the correct syntax to access the elements of the array or pointer.
3.
Can this error occur in other programming languages?
This error is specific to C and C++ languages. However, similar errors can occur in other languages when trying to access elements of a data structure using incorrect syntax or data types.
4.
Can this error be caught during runtime?
No, this error is a compile-time error, meaning it occurs during the compilation process and must be resolved before the program can be executed.
5.
What is the subscript operator []
?
The subscript operator []
is used to access elements of arrays and pointers in C and C++ programming languages.
- Arrays in C
- Pointers in C and C++
- C Error Handling
- C++ Error Handling
Look at your code:
int i1, i2,x,y ;
for (x=0 ;x<10; x++) { ... } for (y=0 ; y<10; y++) { ... }
for(i=0; i<h; i++) { xx[i]= x[i]*x[i]; yy[i]= y[i]*y[i]; } for(i=0;i<h;i++) { sum_x+=x[i]; sum_y+=y[i]; sum_xx+= xx[i]; sum_yy+=yy[i]; sum_xy+= x[i]*y[i]; }
You can’t declare an integer and treat it as an array — equally, you can’t declare an array and treat it as an integer!
I suspect that your x
and y
should be m
and n
, but your code is too «student grade» for me to work it out, and I have no idea what you are actually trying to get it to do.
Do yourself a couple of favours: pick an indentation style, and stick to it. Then indent your code uniformly, so it’s obvious what is what — at the moment that’s all over the place, and it’s much harder to read as a result. And stop using single character variable names: it means that nobody — not even you, obviously — is sure what variable does what. And that makes your code really difficult to work out. Use meaningful names and your code starts to self document, and that means it’s much easier to read and a lot harder to use the wrong variables as you have. That’s why your code is «student grade»! :laugh:
XChr 0 / 0 / 1 Регистрация: 13.11.2013 Сообщений: 84 |
||||||||
1 |
||||||||
14.05.2015, 05:16. Показов 22645. Ответов 9 Метки нет (Все метки)
Есть 2 массива:
При попытке присвоить значение
Выскакивает ошибка:subscripted value is neither array nor pointer nor vector. Как исправить?
0 |
6044 / 2159 / 753 Регистрация: 10.12.2010 Сообщений: 6,005 Записей в блоге: 3 |
|
14.05.2015, 08:25 |
2 |
Переменная а как объявлена?
0 |
XChr 0 / 0 / 1 Регистрация: 13.11.2013 Сообщений: 84 |
||||
14.05.2015, 10:06 [ТС] |
3 |
|||
Как
0 |
HighPredator 6044 / 2159 / 753 Регистрация: 10.12.2010 Сообщений: 6,005 Записей в блоге: 3 |
||||
14.05.2015, 10:30 |
4 |
|||
XChr, в смысле
?
0 |
XChr 0 / 0 / 1 Регистрация: 13.11.2013 Сообщений: 84 |
||||
14.05.2015, 10:35 [ТС] |
5 |
|||
Да, так. Т.е. всё вместе выглядит вот так:
И при попытке присвоения какого-либо элемента tmp3[i][0] к a[i][0] выходит сообщение об ошибке
0 |
6044 / 2159 / 753 Регистрация: 10.12.2010 Сообщений: 6,005 Записей в блоге: 3 |
|
14.05.2015, 11:29 |
6 |
У меня приведенный вами код компилится и отрабатывает нормально (если убрать строку 9). Добавлено через 28 секунд
0 |
XChr 0 / 0 / 1 Регистрация: 13.11.2013 Сообщений: 84 |
||||||||
14.05.2015, 11:54 [ТС] |
7 |
|||||||
Значит, дело в стройке
, которая находится в цикле
Я просто даже не подозревал, что дело в ней, и поэтому не стал копировать в код
0 |
6044 / 2159 / 753 Регистрация: 10.12.2010 Сообщений: 6,005 Записей в блоге: 3 |
|
14.05.2015, 12:02 |
8 |
И кто у нас tmp?
0 |
XChr 0 / 0 / 1 Регистрация: 13.11.2013 Сообщений: 84 |
||||
14.05.2015, 13:59 [ТС] |
9 |
|||
Вот где оказывается ошибка была, спасибо) Но теперь программа вылетает при попытке печати
0 |
DrOffset 17425 / 9258 / 2263 Регистрация: 30.01.2014 Сообщений: 16,212 |
||||
14.05.2015, 14:51 |
10 |
|||
XChr, цикл в 113 строке. Скобки нужны ему. Следующая за циклом операция выполняется в теле цикла, а вот printf уже вне его.
1 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
14.05.2015, 14:51 |
10 |
Overview
These C compile/build errors and warnings are talked about largely in relation to embedded systems (i.e. microcontrollers).
“pointer of type void used in arithmetic”
Usually occurs when you are doing memory arithmetic, and can actually be a warning you ignore!
|
|
“elf section ‘.bss’ will not fit in region ‘ram’
C build error ‘elf section ‘.bss’ will not fit in region ‘ram’
The .bss section contains all 0-initialized global and static variables. This error normally occurs when you have overly large static variables, or you haven’t allocated the stack/heap sizes correctly.
“Suggested parenthesis around assignment used as a truth value”
A warning message from the C compiler.
This is usually because you’ve forgotten to add the second =
in the if statement.
|
|
“Subscripted value is neither array nor pointer”
The C build error ‘subscripted value is neither array nor pointer’.
Normally occurs when you try and index something like an array which isn’t. For example…
|
|
“#pragma once in main file”
The C compiler warning ‘#pragma once in main file’ which occurs when the directive ‘#pragma once’ is incorrectly placed in a .c file.
This occurs when you incorrectly write “#pragma once” in a .c file (even though the error would suggest it, it doesn’t have to be main.c). “#pragma once” is a header guard which prevents an .h file from being included twice in a project and causing multiple declaration/definition errors. Hence “#pragma once” should be only place in .h files. It is an alternative to the “#ifndef” header guard style (see this page for more info).
“variable or field declared void”
The C build error ‘Variable or field declared void’.
This can occur when you declare/define a function in C++ and the compiler doesn’t recognise one of the data types used for an input variable. It will precede a <variable> was not declared in scope
error.
|
|
“macro names must be identifiers”
If you get the error macro names must be identifiers it is usually because you have been using both #if()
and #ifdef
directives, and accidentally used the combination #ifdef()
. This is not allowed! When using #ifdef
, do not enclose the proceeding identifier with brackets.
|
|
“Not In Formal Parameter List”
The ‘not in formal parameter list’ build error is most likely to occur when you have forgotten to add the semi-colon at the end of a function declaration.
Applies To: Keil C51 Compiler
The “not in formal parameter list” build error is most likely to occur when you have forgotten to add the semi-colon at the end of a function declaration. Without the semi-colon, the compiler continues to read onto the following lines, and usually produces this error. Check the first first function declaration preceding this error for a missing semi-colon.
|
|
double free or corruption
Error Type: Run Time
This error normally codes with another keyword at the end, e.g.
|
|
It normally occurs when you accidentally free()
the same piece of memory twice. I have also got this error due to a incremental-build bug in the Xilinx SDK (xsdk) for it’s Zynq FGPAs/microcontroller chips.