试图找出访问数组元素的方法不同? [英] Trying to find different methods of accessing array elements?

查看:121
本文介绍了试图找出访问数组元素的方法不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C,但她决心学习好C.我需要你的帮助。虽然练阵列,我只是想找出我访问数组元素的方法是正确的或者有可能是一个更好的方式来做到这一点。请检查下面的code和建议使用数组指针的一个好办法。
我真的AP preciate如果有人能指导我的教程与指针数组提前练习。

  INT的main()
{
   unsigned int类型I,J;
   无符号整型ARR1 [] = {1,2,3,4,5,6,7,8,9};   无符号整型* ptr_arr =(unsigned int类型*)malloc的(sizeof的(无符号整数));
   ptr_arr = ARR1;   对于(i = 0; I< = 8;我++)
   {
         的printf(在位置值%d个\\ t为:%d个\\ N,我*(ptr_arr + I));
         的printf(\\ n);
         的printf(我的价值%d个和%d个\\ N值,我,ptr_arr [I]);
   }   返回0;
}


解决方案

您的程序正在泄漏内存


  

无符号整型* ptr_arr =(unsigned int类型*)malloc的(sizeof的(无符号整数));


有没有必要为ptr_arr分配内存。

ARR1地址分配足够


  

ptr_arr = ARR1;


要使用另一种方式是,每次递增指针,并用它

  ptr_array2 = ARR1
    的for(int i = 0; I< 8;我++)
    {
       的printf(%d个,* ptr_array2);
       ptr_array2 ++;
     }

I am new to C but determined to learn good C. I need your help. While practising arrays, I just thought to find out that the way I am accessing array element is right or maybe there might be a better way to do it. Please check the following code and suggest a good way of using array with pointers. I would really appreciate if somebody can guide me to a tutorial for advance practice of array with pointers.

int main()
{
   unsigned int i, j;
   unsigned int arr1[] = {1,2,3,4,5,6,7,8,9};

   unsigned int * ptr_arr = (unsigned int *)malloc(sizeof(unsigned int));
   ptr_arr = arr1;

   for(i=0;i<=8;i++)
   {
         printf("Value at location %d\t is:  %d\n",i,*(ptr_arr+i));
         printf("\n");         
         printf("Value of i %d and value at %d\n",i, ptr_arr[i]);
   }

   return 0;
}  

解决方案

You program is leaking memory

unsigned int * ptr_arr = (unsigned int *)malloc(sizeof(unsigned int));

There is no need to allocate memory for ptr_arr.

assignment of address of arr1 is enough

ptr_arr = arr1;

Another way to use it is increment the pointer every time and use it

    ptr_array2 = arr1
    for (int i = 0; i < 8 ; i++)
    {
       printf ("%d", *ptr_array2);
       ptr_array2++;
     }

这篇关于试图找出访问数组元素的方法不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆