Why do I see a cast to signed integer on my unsigned array index?
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
We explain here why even if the index of an array is unsigned, Polyspace says that there is conversion to signed integer
Réponse acceptée
MathWorks Support Team
le 17 Juil 2012
Example of implicit cast from unsigned to signed:
unsigned int r;
int tab[3] = {1,2,3};
void f(void) {
int x;
x = tab[r];
// check details on 'r' says :
// global variable 'r' (unsigned int 32): full-range [0 .. 2^32 -1]
// conversion from unsigned int 32 to int 32
}
The C Standard says that array indexes are (signed) integers. The reason behind that is that pointers and arrays are close in C.
For example, tab[index] is strictly equivalent to *(tab + index).
You can use pointer arithmetic with negative values, hence an array index can be negative.
Exemple of valid array access with a negative index:
void f(void) {
int x;
int *p;
int tab[3] = {1,2,3};
p = &tab[2]; // points to the 3rd element
x = p[-1]; // x is assigned to the second element, '2'
}
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Command-Line Only Options dans Help Center et File Exchange
Produits
Version
Aucune version saisie pour le moment.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!