[英]Why this code giving me a segmentation fault?
#include <stdio.h>
int main()
{
int i,a;
int* p;
p=&a;
for(i=0;i<=10;i++)
{
*(p+i)=i;
printf("%d\n",*(p+i));
}
return 0;
}
I tried to assign numbers from 0 to 10 in a sequence memory location without using an array.我尝试在不使用数组的情况下在序列 memory 位置分配从 0 到 10 的数字。
a
is only an integer. not an array. a
只是一个 integer。不是数组。
you need to declare it differently:你需要以不同的方式声明它:
int i, a[10];
You are trying to write to memory that it does not have permission to access.您正在尝试写入它没有访问权限的 memory。 The variable a is a local variable in the main function, and it is stored on the stack.
变量a是main function中的局部变量,存放在栈中。 The pointer p is initialized to point to the address of a.
指针 p 被初始化为指向 a 的地址。 The code then attempts to write to the memory addresses starting at p and going up to p+10.
然后代码尝试写入从 p 开始到 p+10 的 memory 地址。 However, these memory addresses are not part of the memory that has been allocated for the program to use, and so the program receives a segmentation fault when it tries to write to them.
但是,这些 memory 地址不是已分配给程序使用的 memory 的一部分,因此程序在尝试写入它们时会收到分段错误。
To fix this issue, you can either change the loop condition to a smaller value, or you can allocate memory dynamically using malloc or calloc and assign the pointer to the returned address.要解决此问题,您可以将循环条件更改为较小的值,或者可以使用 malloc 或 calloc 动态分配 memory 并将指针分配给返回的地址。 This will allow you to write to the allocated memory without causing a segmentation fault.
这将允许您写入分配的 memory 而不会导致分段错误。
Like this:像这样:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int* p = malloc(sizeof(int) * 11); // Allocate memory for 10 integers
if (p == NULL) { // Check for allocation failure
printf("Error allocating memory\n");
return 1;
}
for(i=0;i<=10;i++)
{
*(p+i)=i;
printf("%d\n",*(p+i));
}
free(p); // Free the allocated memory when you are done with it
return 0;
}
You can not.你不能。 Memory of int is 4 bytes and you can store only single number in that memory.
int 的 Memory 是 4 个字节,您只能在该 memory 中存储单个数字。
for int: -2,147,483,647 to 2,147,483,647对于整数:-2,147,483,647 到 2,147,483,647
for unsigned int: 0 to 4, 294, 967 295对于无符号整数:0 到 4、294、967 295
There are other types you can use with different sizes, but if you want to put different numbers into one variable you need to use array.您可以使用不同大小的其他类型,但如果您想将不同的数字放入一个变量中,则需要使用数组。
int arr[10];
arr[0] = 0;
arr[1] = 5;
something like this.像这样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.