简体   繁体   中英

Segmentation Fault when using pointer to iterate through array

I have the following code which I am using to iterate through an array that I created. However, one line is currently giving me a segmentation fault.

#include <stdio.h>

int main(){

  int practice[] = {7, 2, 3, 3, 5};
  int *ip;
  int i = 0;

  *ip = practice[0]; //this is the line giving me problems

  for(; i < 5; ++i){
    printf("%d ", *ip);
    ++ip;
  }

  printf("\n\n");

  return 0;
}

I notice when I change the line: *ip = practice[0] to ip = &(practice[0]) the code suddenly works. I am not sure why this happening as the first line seems just as logical as the second.

Since integer pointer ip is uninitialized it contains garbage value. Now when you try to dereference it by *ip and try to assign a value to the memory location pointed by it, you get a segmentation fault.

You should first assign a valid address before dereferencing the pointer.

int *ip; 
ip = practice;

What is happening here:

*ip = practice[0];

Is that you are trying to assign an integer to a pointer variable.

The square brackets are C-language's way to access the actual data, not a reference of it.

Now, when you used the & sign,which is used to get the memory address of this data, this assigned the address of this data to your variable, which what it is exactly expecting.

If you wish to iterate over the array using the pointer instead of a loop, you may want to do this:

ip = practice;

This will assign the address of the first element in the array to your ip variable, allowing you to increment it inside your loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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