C语言 你如何遍历指针?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29909195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:53:37  来源:igfitidea点击:

How do you iterate through a pointer?

cpointers

提问by svsav

For example:

例如:

int *start;
start = (int*)malloc(40);

If I wanted to iterate through all 40 bytes, how would I do so? I tried doing something like:

如果我想遍历所有 40 个字节,我该怎么做?我尝试做类似的事情:

while(start != NULL){
     start++;
}

but that iterates through a massive number of values, which is much greater than 40. Thus, how do you ensure that you iterate through all 40 bytes.

但这会遍历大量值,远远大于 40。因此,您如何确保遍历所有 40 个字节。

Thanks for all the help.

感谢所有的帮助。

采纳答案by fkl

There are two issues here.

这里有两个问题。

A single ptr++skips as many bytes as the type of elementit points to.

单个ptr++跳过与其指向的元素类型一样多的字节

Here the type is int, so it would skip 4 bytes each time(assuming a 32 bit machine since integer is 4 bytes (32 bits) there).

这里的类型是int,所以每次都会跳过4 个字节(假设是 32 位机器,因为那里的整数是 4 个字节(32 位))。

If you want to iterate through all 40 bytes (one byte at a time), iterate using say a chardata type (or type cast your int*to char*and then increment)

如果您想遍历所有 40 个字节(一次一个字节),请使用char数据类型进行迭代(或将您的类型转换int*为 tochar*然后递增)

The other problem is your loop termination.

另一个问题是您的循环终止。

There is no one putting a NULLat the end here, so your loop would keep running (and pointer advancing forward) until it runs into may be a null or goes out of your allotted memory area and crashes. The behavior is undefined.

没有人将 aNULL放在最后,因此您的循环将继续运行(并且指针向前推进),直到它遇到可能为空或超出分配的内存区域并崩溃为止。行为未定义

If you allocated 40 bytes, you have to terminate at 40 bytes yourself.

如果分配了 40 个字节,则必须自己在 40 个字节处终止。

Update:

更新:

Based upon a comment cum down vote to the original question, it is worth mentioning that type casting the result of malloc is not a good idea in C. The primary reason is that it could potentially tamper a failed allocation. It is a requirement in C++ though. The details can be found in the exact same question on SO. Search "casting return value of malloc"

基于对原始问题的评论和反对票,值得一提的是,在 C 中对 malloc 的结果进行类型转换并不是一个好主意。主要原因是它可能会篡改失败的分配。不过,这是 C++ 中的要求。详细信息可以在关于 SO 的完全相同的问题中找到。搜索“铸造malloc的返回值

回答by 2501

First of all, you should be allocating ints correctly:

首先,您应该int正确分配s:

int* start = malloc( sizeof( int )*40 ) ;

Then you can use array subscripting:

然后你可以使用数组下标:

for( size_t i = 0 ; i < 40 ; i++ )
{
    start[i] = 0 ;
}

or a pointer to the end of the allocated memory:

或指向已分配内存末尾的指针:

int* end = start+40 ;
int* iter = start ;

while( iter < end )
{
    *iter= 0 ;
    iter++ ;
}

回答by Daniel Rudy

Arrays represent contiguous blocks of memory. Since the name of the array is basically a pointer to the first element, you can use array notation to access the rest of the block. Remember though, there is no error checking by C on the bounds of the array, so if you walk off the end of the memory block, you can do all kinds of things that you didn't intend and more than likely will end up with some sort of memory fault or segmentation error. Since your int can be variable size, I would use this code instead:

数组代表连续的内存块。由于数组的名称基本上是指向第一个元素的指针,因此您可以使用数组表示法访问块的其余部分。但是请记住,C 不会对数组的边界进行错误检查,因此如果您离开内存块的末尾,您可以做各种您不打算做的事情,而且很可能会以某种内存错误或分段错误。由于您的 int 可以是可变大小,因此我将使用以下代码:

int *start;
int i;

start = malloc(40 * sizeof(int));

for (i = 0; i < 40; i++)
  {
    start[i] = 0;
  }

Something like that will work nicely. The way that you are doing it, at least from the code that you posted, there is no way to stop the loop because once it exceeds the memory block, it will keep going until it runs into a NULL or you get a memory fault. In other words, the loop will only exit if it runs into a null. That null may be within the block of memory that you allocated, or it may be way beyond the block.

这样的事情会很好地工作。您这样做的方式,至少从您发布的代码来看,无法停止循环,因为一旦超出内存块,它将继续运行,直到遇到 NULL 或出现内存错误。换句话说,循环只有在遇到空值时才会退出。该空值可能在您分配的内存块内,也可能远远超出该块。

EDIT: One thing I noticed about my code. It will allocate space for 40 ints which can be either 4 bytes, 8 bytes, or something else depending on the architecture of the machine you are working on. If you REALLY only want 40 bytes of integers, then do something like this:

编辑:我注意到我的代码的一件事。它将为 40 个整数分配空间,可以是 4 字节、8 字节或其他,具体取决于您正在使用的机器的架构。如果你真的只想要 40 个字节的整数,那么做这样的事情:

int *start;
int i;
int size;

size = 40/sizeof(int);
start = malloc(size);
for (i = 0; i < size; i++)
  {
    start[i] = 0;
  }

Or you can use a char data type or an unsigned char if you need to. One other thing that I noticed. The malloc function returns a void pointer type which is compatible with all pointers, so there is no need to do a typecast on a malloc.

或者,如果需要,您可以使用 char 数据类型或 unsigned char。我注意到的另一件事。malloc 函数返回一个与所有指针兼容的空指针类型,因此不需要对 malloc 进行类型转换。

回答by Jonathan Bedard

Well arrays in C aren't bounded so, a few options, the most common:

C 中的数组没有界限,所以有几个选项,最常见的:

int *start;
int cnt = 0;
start = (int*)malloc(sizeof(int)*40);;

while(cnt<40)
{
    start++;
    cnt++;
}

Another option:

另外一个选项:

int *start;
int *ref;
start = ref = (int*)malloc(sizeof(int)*40);

while(start != ref+40)
    start++;

And this last one is the closest to what you seem to mean to do:

而这最后一个最接近您似乎想要做的事情:

int *start;
start = ref = (int*)malloc(sizeof(int)*41);
start[40] = -1;

while((*start) != -1)
    start++;

I would suggest reading more on how pointers in C work. You don't appear to have a very good grasp of it. Also, remember that C takes off the training wheels. Arrays aren't bounded or terminated in a standard way, and a pointer (address in memory) will never be NULL after iterating through an array, and the contents a pointer is pointing to could be anything.

我建议阅读更多关于 C 中指针如何工作的内容。你似乎没有很好地掌握它。另外,请记住 C 会卸下辅助轮。数组没有以标准方式有界或终止,并且指针(内存中的地址)在遍历数组后永远不会为 NULL,并且指针指向的内容可以是任何内容。