C11dr 6.5.2.1 Array subscripting … «One of the expressions shall have type ‘‘pointer to complete object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.» …
With []
, you get to do:
// pointer_type[integer_type]
float data[];
int n;
float total;
total = data[n];
// or the unconventional equivalent
// integer_type[pointer_type]
total = n[data]; // But let's leave that for another post
// Instead the OP did
// pointer_type[pointer_type]
// and received error: "Array subscript is not an integer"
float *p;
total = data[p];
The usage of float
is not the issue here, but the usage of a pointer.
An integer type includes types int
, unsigned
, size_t
, long
, etc.
I think the OP wanted the following (or something like this)
float deviation(float data[], int n) {
if (i <= 0) return 0;
float data_average = average(data, n);
float total = 0.0; // don't forget to set to 0.0
float *p = data;
while (p < (data + n)) {
total += (*p - data_average) * (*p - data_average);
p++;
}
return sqrt(total / n); // div by 0 averted
}
following this previous question Malloc Memory Corruption in C, now i have another problem.
I have the same code. Now I am trying to multiply the values contained in the arrays A * vc
and store in res. Then A is set to zero and i do a second multiplication with res and vc and i store the values in A. (A and Q are square matrices and mc and vc are N lines two columns matrices or arrays).
Here is my code :
int jacobi_gpu(double A[], double Q[],
double tol, long int dim){
int nrot, p, q, k, tid;
double c, s;
double *mc, *vc, *res;
int i,kc;
double vc1, vc2;
mc = (double *)malloc(2 * dim * sizeof(double));
vc = (double *)malloc(2 * dim * sizeof(double));
vc = (double *)malloc(dim * dim * sizeof(double));
if( mc == NULL || vc == NULL){
fprintf(stderr, "pb allocation matricren");
exit(1);
}
nrot = 0;
for(k = 0; k < dim - 1; k++){
eye(mc, dim);
eye(vc, dim);
for(tid = 0; tid < floor(dim /2); tid++){
p = (tid + k)%(dim - 1);
if(tid != 0)
q = (dim - tid + k - 1)%(dim - 1);
else
q = dim - 1;
printf("p = %d | q = %dn", p, q);
if(fabs(A[p + q*dim]) > tol){
nrot++;
symschur2(A, dim, p, q, &c, &s);
mc[2*tid] = p; vc[2 * tid] = c;
mc[2*tid + 1] = q; vc[2*tid + 1] = -s;
mc[2*tid + 2*(dim - 2*tid) - 2] = p; vc[2*tid + 2*(dim - 2*tid) - 2 ] = s;
mc[2*tid + 2*(dim - 2*tid) - 1] = q; vc[2 * tid + 2*(dim - 2*tid) - 1 ] = c;
}
}
for( i = 0; i< dim; i++){
for(kc=0; kc < dim; kc++){
if( kc < floor(dim/2)) {
vc1 = vc[2*kc + i*dim];
vc2 = vc[2*kc + 2*(dim - 2*kc) - 2];
}else {
vc1 = vc[2*kc+1 + i*dim];
vc2 = vc[2*kc - 2*(dim - 2*kc) - 1];
}
res[kc + i*dim] = A[mc[2*kc] + i*dim]*vc1 + A[mc[2*kc + 1] + i*dim]*vc2;
}
}
zero(A, dim);
for( i = 0; i< dim; i++){
for(kc=0; kc < dim; k++){
if( k < floor(dim/2)){
vc1 = vc[2*kc + i*dim];
vc2 = vc[2*kc + 2*(dim - 2*kc) - 2];
}else {
vc1 = vc[2*kc+1 + i*dim];
vc2 = vc[2*kc - 2*(dim - 2*kc) - 1];
}
A[kc + i*dim] = res[mc[2*kc] + i*dim]*vc1 + res[mc[2*kc + 1] + i*dim]*vc2;
}
}
affiche(mc,dim,2,"Matrice creuse");
affiche(vc,dim,2,"Valeur creuse");
}
free(mc);
free(vc);
free(res);
return nrot;
}
When i try to compile, i have this error :
jacobi_gpu.c: In function ‘jacobi_gpu’:
jacobi_gpu.c:103: error: array subscript is not an integer
jacobi_gpu.c:103: error: array subscript is not an integer
jacobi_gpu.c:118: error: array subscript is not an integer
jacobi_gpu.c:118: error: array subscript is not an integer
make: *** [jacobi_gpu.o] Erreur 1
The corresponding lines are where I store the results in res and A :
res[kc + i*dim] = A[mc[2*kc] + i*dim]*vc1 + A[mc[2*kc + 1] + i*dim]*vc2;
and
A[kc + i*dim] = res[mc[2*kc] + i*dim]*vc1 + res[mc[2*kc + 1] + i*dim]*vc2;
Can someone explain me what is this error and how can i correct it?
Thanks for your help.
Schol-R-LEA
1,446
Commie Mutant Traitor
Featured Poster
8 Years Ago
in the line in question:
sum[M][3] = inputarray[M][3] + inputarray2[M][3];
You are treating inputarray()
and inputarray2()
as arrays, rather than calling them as functions. The correct syntax would be:
sum[M][3] = inputarray(M, 3) + inputarray2(M, 3);
BTW, I strongly recommend you get into the practice of indenting your code suitably. The usual practice is to indent one level — three to eight spaces, depending on your indent style — every time you have a block of code that is inside a loop or an if statement. This practice, called ‘nesting’, is very important. The goal of formatting code is to make the nesting levels explicit in the layout of the program. While in C, it is purely for the benefit of the programmer, it should make reading and editing the code easier, which is why it is important to get into the habit as soon as you can. I recommend reading this article on the subject for further clarification.
Now, as this Wikipedia entry explains, there are several different styles which one can use to indent their code; what is important is not the specific style, but consistency in applying your chosen style. As long as you follow the main rule — indent inside a block, de-dent after the end of a block — you should be able to use the style you are comfortable with, **so long as you are consistent in appyling it*. those two rules are the real key; as long as your code makes the nesting express, and you don’t change styles in the middle of a program, your good.
Fortunately, there exist several editors and styling programs that will format code automatically for you. I recommend AStyle as a simple one you can download and run on your computer. By default, it formats to Allman Style with an indent of four, but it is configurable to several different styles. If you download Code::Blocks, it includes AStyle as a plugin which can be called from the editor.
Here is your code agin, but formatted with AStyle:
#include <stdio.h>
void inputarray(int arg[][3], int rows);
void printarray (int arg[][3], int rows);
void inputarray2(int arg[][3], int rows);
void printarray2(int arg[][3], int rows);
int main ()
{
int M[3][3];
int action, sum=0;
inputarray(M,3);
printarray(M,3);
inputarray2(M,3);
printarray2(M,3);
printf("1:Add the matrices");
printf("2:Subtract the matrices");
printf("3:Multiply the matrices");
printf("4:EXIT");
printf("Please enter your choice(1-4): ");
scanf("%d", &action);
switch(action) {
case 1: {
sum[M][3] = inputarray(M, 3) + inputarray2(M, 3);
printf("Sum of entered matrices:-n");
printf("%d", sum[M][3]);
printf("n");
break;
}
}
return 1;
}
void inputarray(int arg[][3], int rows)
{
int row,col;
for(row=0; row<rows; row++)
{
printf("3 numbers for Row %d for first matrix : ",(row+1));
for(col=0; col<3; col++)
scanf("%d",&arg[row][col]);
}
}
void printarray (int arg[][3], int rows)
{
int x, y;
for (x=0; x<rows; x++)
{
for(y=0; y<3; y++)
printf("%dt",arg[x][y]);
printf("n");
}
printf("n");
}
void inputarray2(int arg[][3], int rows)
{
int row,col;
for(row=0; row<rows; row++)
{
printf("3 numbers for Row %d of second matrix : ",(row+1));
for(col=0; col<3; col++)
scanf("%d",&arg[row][col]);
}
}
void printarray2 (int arg[][3], int rows)
{
int x, y;
for (x=0; x<rows; x++)
{
for(y=0; y<3; y++)
printf("%dt",arg[x][y]);
printf("n");
}
printf("n");
}
Edited
8 Years Ago
by Schol-R-LEA
-
11-06-2012
#1
Registered User
array subscript is not an integer
im getting the error when compiling the code…
Code:
float array[20]; int last; array[last[array]]; how to get red of this
-
11-06-2012
#2
SAMARAS
You have
Code:
array[last[array]];
In general,if you are sure you want something like this,imagine it with numbers and arrays.It would be something like this
if you want to access the index described by the last element of the array.
So maybe you want to say
-
11-06-2012
#3
Registered User
still the same error,i think may be its due to types of the integer variable and float arrays
-
11-06-2012
#4
SAMARAS
Have you initialized variable last? Can you please post the code you complied?
-
11-06-2012
#5
Registered User
im just checking the syntax errors
i have initialised int last = n-1;
int *l ;
l = &last;
-
11-06-2012
#6
SAMARAS
What is n?Where is the array you were talking about?
Just post all the code you have (i consider it is small from what you say)
Also it would be very kind of you if you could wrap your code in code tags.It is easy
[key]/*Your code here*/[/key] Replace key with code in order this to work.EDIT : it is ok to say
Code:
int a=5; int* p; p=&a;
Last edited by std10093; 11-06-2012 at 05:17 AM.
-
11-06-2012
#7
Registered User
Originally Posted by prathiksa
still the same error,i think may be its due to types of the integer variable and float arrays
Yes it is.
Arrays can only be indexed using values that have integral type (char, int, long, unsigned, etc). They cannot be indexed using non-integral values (float as in your case, struct types, etc).
There is also an obscure corner of C that causes «array[index]» and «index[array]» to be equivalent (assuming array is (well….) an array or a pointer, and index has integral type). Because of that, your expression «array[last[array]]» is equivalent to «array[array[last]]» which attempts to use array[last] as an index. In your code, array[last] is of type float so is not a valid index. Hence the compiler error.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
-
11-06-2012
#8
SAMARAS
What i thought you wanted to do
Code:
#include <stdio.h> int main( int argc, char *argv[]) { float array[5]; int last = 4; array[0]=1.2; array[1]=1.3; array[2]=1.4; array[3]=1.5; array[4]=1.9; printf("%fn",array[last]); return(0); }
grumpy is more experienced,so he is sure to have it better in his mind
-
11-06-2012
#9
Algorithm Dissector
You get rid of the error by fixing or removing the nonsense code.
Explain what you really want to do and we’ll show you how to write code for it that makes sense.My homepage
Advice: Take only as directed — If symptoms persist, please see your debuggerLinus Torvalds: «But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong»
Spotter 30 / 21 / 11 Регистрация: 09.11.2010 Сообщений: 240 |
||||
1 |
||||
02.05.2011, 20:31. Показов 8346. Ответов 12 Метки нет (Все метки)
Выдаёт на компиляции такую ошибку error C2108: subscript is not of integral type
__________________
0 |
623 / 467 / 57 Регистрация: 28.01.2011 Сообщений: 605 |
|
02.05.2011, 20:33 |
2 |
Индексы массива должны быть целочисленного типа, а у вас i и j объявлены как double. Либо делайте приведение типов в цикле, либо объявляйте их как int.
0 |
1551 / 917 / 193 Регистрация: 26.03.2010 Сообщений: 3,105 |
|
02.05.2011, 20:34 |
3 |
И подключите stdio.h
0 |
1067 / 846 / 60 Регистрация: 30.04.2011 Сообщений: 1,659 |
|
02.05.2011, 20:45 |
4 |
И подключите stdio.h 1. cstdio — по стандарту
0 |
Spotter 30 / 21 / 11 Регистрация: 09.11.2010 Сообщений: 240 |
||||
02.05.2011, 20:55 [ТС] |
5 |
|||
Ma3a, Сделал, как Вы сказали, компилируется, ввожу массив 3х3 действительных чисел, но при выводе этого массива, выводится огрмнейшое число, а не сам массив. Вот код вывода:
neske, Ну вообще-то, если вы не заметили, я только часть кода сюда скинул, где ошибка, всё у меня подключено.
0 |
ValeryLaptev 1067 / 846 / 60 Регистрация: 30.04.2011 Сообщений: 1,659 |
||||
02.05.2011, 21:00 |
6 |
|||
Здесь у тебя нет никаких пробелов между значениями. Поэтому все подряд выводится…
0 |
5038 / 2617 / 241 Регистрация: 07.10.2009 Сообщений: 4,310 Записей в блоге: 1 |
|
02.05.2011, 21:04 |
7 |
1. cstdio — по стандарту для Си++ да, для Си stdio.h, судя по коду, это Си
2. Если работа в Студии, то она сама автоматом подключает. нэ? и даже если так, то это не оправдание.
0 |
30 / 21 / 11 Регистрация: 09.11.2010 Сообщений: 240 |
|
02.05.2011, 21:05 [ТС] |
8 |
ValeryLaptev, Ни в этом дело, выводится вообще много цифр, и близко не похожих на те значения, которые я ввожу в массиве.
0 |
623 / 467 / 57 Регистрация: 28.01.2011 Сообщений: 605 |
|
02.05.2011, 21:06 |
9 |
Spotter, еще у вас массив типа double, а в scanf вы используете «%f» для ввода, ей требуется «%lf» для ввода double, так она не поймет(ну или поймет неправильно).
2 |
30 / 21 / 11 Регистрация: 09.11.2010 Сообщений: 240 |
|
02.05.2011, 21:20 [ТС] |
10 |
Ma3a, Спасибо, всё работает теперь правильно )) Ещё маленький вопрос (постоянно забываю такую мелочь, и сейчас никак вспомнить не могу), как правильно указать, сколько знаков после запятой выводить? )
0 |
623 / 467 / 57 Регистрация: 28.01.2011 Сообщений: 605 |
|
02.05.2011, 21:22 |
11 |
%.4f — выведет, например, 4 знака после запятой.
1 |
1067 / 846 / 60 Регистрация: 30.04.2011 Сообщений: 1,659 |
|
02.05.2011, 21:24 |
12 |
%10.6f — всего, после запятой
0 |
ivan777 2 / 1 / 3 Регистрация: 10.03.2010 Сообщений: 65 |
||||
11.06.2011, 18:38 |
13 |
|||
Spotter, Вот так:
Где 6.2 отвечают за то сколько знаков вывести после комы, если написать 6.3 то выведет 3 знака после комы, еще можно писать 4.2 но не помню какая разница. Если у тебя число припустим 7.777 и вы выводите всего лишь 2 знака после комы то произойдет округление.
0 |
wvdk
New Member
- Total Posts : 29
- Reward points : 0
- Joined: 2019/02/11 03:36:51
- Location: 0
- Status: offline
Hi lubin,
I am stuck with the following error while compiling a simple model with the SPI function block on an dsPIC33FJ256GP710A.
when I use the SPI block and (by example) activate an input port to write data on the SPI, I get an error when compiling the code: «Array subscript is not an integer»
If I check the generated code, the indeed, the array position is indicated as (by example)
array1[1.0]
instead of
array1[1]
I have been searching for the cause, but I cannot find the reason. I tried different blocksets (3.46, 3.47, 3.50), i tried different compilers (XC16 1.6, XC16 2.0) but without succes. I have the feeling it might also be something to do with settings in matlab/simulink itself, but I don’t succeed to find the root cause. Can you help me on this one?
Best regards,
Wim
Gort2015
Klaatu Barada Nikto
- Total Posts : 6043
- Reward points : 0
- Joined: 2015/04/30 10:49:57
- Location: 0
- Status: offline
Re: Error: Array subscript is not an integer
2022/04/20 06:16:59
(permalink)
How did you declare array1 ?
array1[1.0] ???
List the compiler output.
int array1[100], j;
j = array1[50];
mbrowning
USNA79
- Total Posts : 2245
- Reward points : 0
- Joined: 2005/03/16 14:32:56
- Location: Melbourne, FL
- Status: offline
Re: Error: Array subscript is not an integer
2022/04/20 06:43:28
(permalink)
The OP didn’t declare the array, Matlab declared the array. The OP is asking support in the Matlab forum (usually Lubin) to help figure out out to make Matlab create legal code.
Lubin
Moderator
- Total Posts : 558
- Reward points : 5
- Joined: 2007/03/31 07:38:15
- Location: Bayonne, France
- Status: offline
Re: Error: Array subscript is not an integer
2022/04/20 11:45:44
(permalink)
Hi Wim,
Could you post a model that trig this issue ?
This looks like an issue with generated code for the SPI peripheral. Using another compiler would not change anything. You might try using a different setting with the SPI peripheral which might not generate the faulty code.
I am currently off, I could look at it in early May.
Thanks, Lubin
Lubin
Moderator
- Total Posts : 558
- Reward points : 5
- Joined: 2007/03/31 07:38:15
- Location: Bayonne, France
- Status: offline
Re: Error: Array subscript is not an integer
2022/05/06 02:22:41
(permalink)
Hi Wim,
I did not reproduced the issue on my side.
If you have a model example to upload, it might help to trig the problem and fix it.
Lubin
Индекс массива не является целым числом
int i;
va_list objects_list;
va_start(objects_list, objects);
for (id o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++);
objectsInArray = malloc(sizeof(id) * i);
va_end(objects_list);
// ... (malloc NULL checking is here, does not involve i)
va_start(objects_list, objects);
for (id o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++) {
objectsInArray[i] = o;
}
va_end(objects_list);
Я получаю Array subscript is not an integer
ошибка на objectsInArray[i] = o;
линии. objectsInArray
объявлен как id *objectsInArray
.
i
есть int
, так почему я получаю эту ошибку и как ее исправить? Заранее спасибо.
i
имеет тип id
внутри цикла for. Чтобы устранить неоднозначный синтаксис, объявите id o
Вне for(...)
заявление.
В Xcode в настройках проекта включите предупреждения для «Скрытых локальных переменных», чтобы компилятор предупреждал о таких вещах. В противном случае при использовании gcc
, Используйте -Wshadow
.
ответ дан 27 мар ’11, в 15:03
Нет, вы создали новый i
который имеет тип id
. К сожалению, в цикле for невозможно выполнить инициализацию в «смешанном режиме».
ответ дан 27 мар ’11, в 14:03
for (id o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++)
включает декларацию
id o = objects, i = 0;
что значит i
это не int
, Но id
. Объявить o
перед циклом:
id o;
for (o = objects, i = 0; o != nil; o = va_arg(objects_list, id), i++)
ответ дан 27 мар ’11, в 14:03
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
objective-c
c
arrays
int
or задайте свой вопрос.