Subscripted value is neither array nor pointer ошибка

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

  1. Understanding the Error
  2. Step-by-Step Solution
  3. FAQs
  4. 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 массива:

C
1
2
3
4
5
6
7
8
9
10
11
12
int **tmp3;
  tmp3 =  ( int  **) malloc(sizeof(int*)*n);
    for  (i=0; i<n; i++)
    {
        tmp3[i]=(int*)malloc(sizeof(int)*m);
    }
 
   a =  ( int  **) malloc(sizeof(int*)*n);
    for  (i=0; i<n; i++)
    {
        a[i]=(int*)malloc(sizeof(int)*m);
    }

При попытке присвоить значение

C
1
tmp3[i][j]=a[i][j]

Выскакивает ошибка: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

Как

C
1
int a**



0



HighPredator

6044 / 2159 / 753

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

Сообщений: 6,005

Записей в блоге: 3

14.05.2015, 10:30

4

XChr, в смысле

C
1
int **a;

?



0



XChr

0 / 0 / 1

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

Сообщений: 84

14.05.2015, 10:35

 [ТС]

5

Да, так. Т.е. всё вместе выглядит вот так:

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
int **a;
int **tmp3;
a =  ( int  **) malloc(sizeof(int*)*n);
    for  (i=0; i<n; i++)
    {
        a[i]=(int*)malloc(sizeof(int)*m);
    }
 
int **tmp3;
  tmp3 =  ( int  **) malloc(sizeof(int*)*n);
    for  (i=0; i<n; i++)
    {
        tmp3[i]=(int*)malloc(sizeof(int)*1);
    }
 
 for (i=0; i<n; i++) // Заполнение массива a
        {
            for (j=0; j<m; j++)
            {
                a[i][j]=(-50+rand()%100);
            }
        }
       
for (i=0;i<n;i++)
       tmp3[i][0]=a[i][0];

И при попытке присвоения какого-либо элемента tmp3[i][0] к a[i][0] выходит сообщение об ошибке



0



6044 / 2159 / 753

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

Сообщений: 6,005

Записей в блоге: 3

14.05.2015, 11:29

6

У меня приведенный вами код компилится и отрабатывает нормально (если убрать строку 9).

Добавлено через 28 секунд
З.Ы. ну и добавить там i,j,m,n



0



XChr

0 / 0 / 1

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

Сообщений: 84

14.05.2015, 11:54

 [ТС]

7

Значит, дело в стройке

C
1
printf ("nЮ:%d",tmp[i][1]);

, которая находится в цикле

C
1
for (i=0;i<n;i++) {  tmp3[i][0]=a[i][0]; printf ("nЮ:%d",tmp[i][1]); }

Я просто даже не подозревал, что дело в ней, и поэтому не стал копировать в код



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

Вот где оказывается ошибка была, спасибо) Но теперь программа вылетает при попытке печати
Залью сюда весь код программы:

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
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <math.h>
 
int main()
{
 
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    printf ("n Характеристикой столбца целочисленной матрицы назовем сумму модулей егоn отрицательных нечётных элементов. Переставляя столбцы заданной n матрицы, расположить их в соответствии с ростом характеристик.nn");
    int **a;
    int i, j, f, n, m;
    printf("nt Введите количество строк: ");
    scanf("%d", &n);
    printf("nt Введите количество столбцов: ");
    scanf("%d", &m);
    int sumk[m],por[m];
    for (i=0; i<m; i++)
    {
        sumk[i]=0;
        por[i]=i;
        printf ("%d",por[i]);
    }
 
    a =  ( int  **) malloc(sizeof(int*)*n);
    for  (i=0; i<n; i++)
    {
        a[i]=(int*)malloc(sizeof(int)*m);
    }
 
 
    printf ("nt Введите 1, чтобы самостоятельно заполнить матрицу.n");
    printf ("nt Введите 0, чтобы заполнить матрицу случайными числами.n ");
 
    scanf ("%d",&f);
 
    if (f==1) // Заполнение матрицы в ручную
    {
        for (i = 0; i < n; i++)
        {
            for (j = 0; j < m; j++)
            {
                printf("nЭлемент [%d][%d] = ", i+1, j+1);
                scanf("%d", *(a+i)+j);
            }
        }
    }
    if (f==0) // Хаполнение матрицы рандомными числами
    {
 
        for (i=0; i<n; i++)
        {
            for (j=0; j<m; j++)
            {
                a[i][j]=(-50+rand()%100);
            }
        }
    }
 
    printf ("n Составленная матрица: nn");
    for (i = 0; i < n; i ++)
    {
        for (j = 0; j < m; j ++)
        {
            printf("%4d", *(*(a+i)+j) );
        }
        printf("n");
    }
 
// Суммирование абсолюьютных значений нечётный отрицательных чисел по столбцам
    j=0;
    while (j<m)
    {
        for (i=0; i<n; i++)
        {
            if (a[i][j]<0 && a[i][j]%2!=0) sumk[j]=sumk[j]+abs(a[i][j]);
        }
        j++;
    }
 
    for (i=0; i<m; i++) printf ("n sumk[%d]=%d",i,sumk[i]);
 
// Сортировка массива индексов и массива сумм по возрастанию
 
 
    int tmp,tmp2;
    for (i=0; i<m-1; i++)
    {
        for (j=i+1; j<m; j++)
        {
            if (sumk[i]>sumk[j])
            {
                tmp=sumk[i];
                tmp2=por[i];
                sumk[i]=sumk[j];
                por[i]=por[j];
                sumk[j]=tmp;
                por[j]=tmp2;
            }
        }
    }
 
for (i=0;i<m;i++) printf ("n%d и %d",sumk[i],por[i]);
 
int **tmp3;
  tmp3 =  ( int  **) malloc(sizeof(int*)*n);
    for  (i=0; i<n; i++)
    {
        tmp3[i]=(int*)malloc(sizeof(int)*n);
    }
 
 for (i=0;i<n;i++)
       tmp3[i][0]=a[i][0];
        printf ("n:%d",tmp3[i][0]);
 
 
    return 0;
}



0



DrOffset

17425 / 9258 / 2263

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

Сообщений: 16,212

14.05.2015, 14:51

10

XChr, цикл в 113 строке. Скобки нужны ему. Следующая за циклом операция выполняется в теле цикла, а вот printf уже вне его.

C
1
2
3
4
5
    for (i = 0; i < n; i++)
    {
        tmp3[i][0] = a[i][0];
        printf ("n:%d", tmp3[i][0]);
    }



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!

1
2
3
4
5
6
void* AppendNewArrayElement(void* arrayStart, uint8 currNumElements, uint8 sizeOfArrayElement) {
    // Create a new option at end of option array
    arrayStart = realloc(arrayStart , (currNumElements+1)*sizeOfArrayElement);
    // Set to 0
    memset(arrayStart + currNumElements*sizeOfArrayElement, '', sizeOfArrayElement);
}

“elf section ‘.bss’ will not fit in region ‘ram’

C build error '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.

A warning message from the C compiler.

This is usually because you’ve forgotten to add the second = in the if statement.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Only one equal sign, if statement will produce unexpected results!
// value2 will be assigned to value1 and then
// checked to see if non-zero
if(value1 = value2) {
    // blah blah
}

// Correct way of comparing two values, with two equal signs
if(value1 == value2) {
    // blah blah
}

“Subscripted value is neither array nor pointer”

The C build error '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…

1
2
3
4
5
6
7
8
9
#include 

double value;

// This will produce the error, as sin is a function, not an array
value = sin[180];

// The proper way of using sin
value = sin(180);

“#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.

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'.

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.

1
2
3
// A function declaration with an unrecognised type used in the input.
// The will cause both a 'variable or field declared void' and 'inputVar was not declared in scope' error
void function1(unrecognisedType_t inputVar);

“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.

1
2
3
4
5
6
7
8
9
// BAD!
#ifdef(__linux)
    ...
#endif

// GOOD!
#ifdef __linux__
    ...
#endif

“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.

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.

1
2
3
4
// The following function declaration is missing a semi-colon at the end
void function1()
// The "not in formal parameter list" build error will occur on this following line
void function2();

double free or corruption

Error Type: Run Time

This error normally codes with another keyword at the end, e.g.

1
double free or corruption (!prev)

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.

Понравилась статья? Поделить с друзьями:
  • Subscript out of range vba excel ошибка
  • Subscript out of bounds ошибка
  • Subquery returns more than 1 row mysql ошибка
  • Subquery returned more than 1 value ошибка
  • Streamlabs obs ошибка при выводе