2012-07-09 117 views
0

可能重复:
array in objective c数组长度

我有疑问如何找到数组的长度.....

我的代码是

#import <Foundation/Foundation.h> 

void myFunction(int i, int*anBray); 


int main(int argc, const char * argv[]) 
{ 
    int anBray[] = {0,5, 89, 34,9,189,9,18,99,1899,1899,18,99,189, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,89, 34,2,600,-2,0}; 
    int i;  

    NSLog (@"Input:"); 
    for (i=0; i<sizeof(anBray)/sizeof(int); i++) 
     NSLog(@ " anBray[%i]= %i ",i,anBray[i]); 

    NSLog (@"Output"); 

    myFunction(i,anBray); 

    return 0; 

} 

void myFunction(int i, int*anBray) { 

    for (i=0; i<anBray; i++) { 
     if (anBray[i] == 0) { 
      anBray[i] = anBray[i+1] - anBray[i]; 
     } else { 
      anBray[i] = anBray[i] - anBray[i]; 
      anBray[i] = anBray[i+1] - anBray[i]; 
     } 
     NSLog(@ " anBray[%i]= %i",i,anBray[i]); 

    } 

} 

在fu nction“void myFunction”它的工作原理,但它也给垃圾值太小,它可以正常工作吗? plz help ...

+4

这个问题与Objective C几乎没有任何关系,更多的是C问题。 Objective C唯一关于它的是你使用NSLog而不是printf()。 Objective C数组通常使用基础类的NSArray完成。 – Chris 2012-07-09 10:48:19

+0

@克里斯:谢谢我已经理解了主题 – AG29 2012-08-14 10:49:30

回答

1

The for(i = 0; i < anBray; i ++){line does not sense。你正试图将一个指针与一个整数进行比较。

要确定数组的大小,您可以像在主函数中那样使用sizeof anBray/sizeof anBray [0]或sizeof anBray/sizeof(int)在特定情况下执行此操作。

但是,在你的myFunction函数中,你接受一个int指针,所以你不能获得指针指向的数组的大小。这个int指针指向anBray的第一个元素。也就是说,以下是等价的:

myFunction(i, anBray); 
myFunction(i, &anBray[0]); 

既然你无法确定从myFunction的数组的大小,则必须通过大小(实际上元素个数,以字节为单位不大小)或使用已知的定点值(例如-1)在数组的末尾进行检测。然后,您可以循环播放,直到你到达终点,例如:

#include <stdio.h> 

void f(int nelem, int *a) { 
    int e; 
    for (e = 0; e < nelem; e++) // Now the element count is known. 
     printf("a[%d] = %d\n", e, a[e]); 
} 

int main(void) { 
    int x[] = { 5, 6, 7, 8 }; 
    // The number of elements in an array is its total size (sizeof array) 
    // divided by the size of one element (sizeof array[0]) 
    // Here we pass it as the first argument to f() 
    f(sizeof x/sizeof x[0], x); 
    return 0; 
} 
+0

我不完全明白你想说什么?请再次澄清 – AG29 2012-07-09 11:36:24

+0

我举了一个例子,您将大小传递给函数。你不明白什么? – Chris 2012-07-09 13:34:10

+0

其实我在这个网站是新的。我的帐户已被阻止。请按作者的要求重新打开我的被阻止的帐户。我不会再次错误。请使用.... – AG29 2012-08-31 09:47:07

0

你不能在C中的任何味道,确定数组(VS,比方说,一个NSArray)的大小,没有尺度声明。这些信息根本就没有得到。一个数组是纯粹作为指向第一个元素的指针传递的,并且没有维数信息与数组一起存储或以某种方式随指针传递。

在像Java这样的语言中,数组本身就是一个对象,其中包含一个包含其维度的标头。但是在C中,数组只是某个地方某个空间的地址。

+0

那么我该如何纠正我的代码? – AG29 2012-07-09 11:35:17

+0

@ user1511571n - 传递维度,使用NSArray等。 – 2012-07-09 11:56:07

+0

有没有任何方法可以在没有NSArray的情况下传递参数或维度 – AG29 2012-07-09 12:49:58