int *c;
int d,noofentries;
struct A
{
unsigned int *ptr;
int entry;
}a;
a->ptr=memalloc(34,unsigned int);
a->ptr = (unsigned int*) entry
nofoentries = 8 ;
d =56749;
for(i=0;i<noofentries;i++)
{
c[i] = d; // how is a pointer treated as array ?
}
for(i=0;i<34;i++)
{
a->ptr[i] = c[i]; //segmentation fault occurs
}
我要求将c[i]
中填充的值分配给a->ptr[i]
。因此,当a->ptr[i]
被删除时,c[i]
也会被释放。
请帮助!!
答案 0 :(得分:1)
通常您不希望将pointer
视为array
,而是拥有array
并使用其name as pointer
至refer to any particular member
数组
例如
int arr[5];
//the array name 'arr' points to the zeroth element
现在您可以使用*(arr+ indexNo) = value or arr[indexNo] = value
为特定元素分配值
当您为其指定了数组时,您可能希望将指针用作数组。
例如
int arr[5];
int *ptr;
如果你这样做
ptr = arr;
您可以像访问arr
一样访问ptr
as
ptr[index]= value;
答案 1 :(得分:1)
指向类型的指针与该类型的数组相同 *(c + x)= a &LT; =&GT; c [x] = a;
c + x找到正确的指针位置,因为它将x * sizeof(type)添加到c指针。
您的代码在gcc下编译:
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
struct A { unsigned int *ptr; int entry; };
int main(int argc, char ** argv)
{
unsigned int * c;
unsigned int d;
int noofentries, i;
struct A a;
noofentries=34;
c=malloc(noofentries * sizeof(unsigned int));
d =56749;
for(i=0;i<noofentries;i++) { c[i] = d; }
// no need to copy full array c, since ptr is a pointer over it...
a.ptr = c;
// warning if above line is not done then allocation of ptr is required:
// a.ptr = malloc(noofentries * sizeof(unsigned int));
// and content copy
// for(i=0;i<noofentries;i++) { a.ptr[i] = c[i]; }
for(i=0;i<noofentries;i++) {
assert( a.ptr[i] == *(c + i) );
printf("a.ptr[%u]=%u\n",i,*(a.ptr + i));
}
free(c);
}