简体   繁体   English

将int数组转换为C中的指针

[英]convert int array to pointer in C

void test()
{
       int buf[1000];

       //populate buf
       foo(buf);//is this correct? Can we pass buf as a pointer that foo expects?



}
void foo(void*ptr)
{}

EDIT: if foo were fwrite, would the above(mechanism of passing buf so as to supply fwrite with content to write into some file) still be applicable? 编辑:如果foo是fwrite,上述(传递buf以便向fwrite提供内容以写入某些文件的机制)是否仍然适用?

Its perfectly valid in C. foo argument is a pointer that can point to any type . 它在foo参数中完全有效,它是一个可以指向任何类型的指针。 When you pass an array, it decays to a pointer pointing to the first element of the array (ie,address location of the first element is passed). 当您传递数组时,它会衰减为指向该数组第一个元素的指针(即,传递第一个元素的地址位置)。 So, 所以,

 ptr -> &buf[0] ;

Yes you can do that. 是的,你可以这么做。

buf is the base pointer of the array. buf是数组的基本指针。

是的,您将始终将buf用作指针。

Yes its correct. 是的,它是正确的。 You can use the "ptr" pointer in your foo function. 您可以在foo函数中使用“ ptr”指针。 http://codepad.org/HwYd0GAh http://codepad.org/HwYd0GAh

As the other answers pointed out, yes , you can pass buf to the function. 正如其他答案所指出的那样, ,您可以将buf传递给该函数。

However, inside the function, the variable ptr has type void* . 但是,在函数内部,变量ptr类型为void* And there's only a few things you can do with ptr itself. 而且ptr本身只能做几件事。 Usually you convert it (with or without a cast) to something relevant, like int* . 通常,您将其转换(带或不带强制转换)为相关的内容,例如int*

void foo(void *ptr) {
    int *iptr;
    iptr = ptr;
    /* now use iptr */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM