I have got zsh: segmentation fault in this program and I don't know why. How run this program without this fault.
#include<stdio.h>
int main()
{
int old[9]={'3','5','7','8','8','6','2','3','5'};
int new[3][3], r, c, n;
for (r=0;r<3;r++){
for (c=0;c<3;c++){
new[r][c]=old[n];
n++;
}
}
printf("New array is:\n");
for (r=0;r<3;r++){
for (c=0;c<3;c++){
printf("%d",new[r][c]);
}
printf("\n");
}
}
┌──(imsourobh㉿kali)-[~/Documents/codes/c/cse] └─$ cd "/home/imsourobh/Documents/codes/c/cse/" && gcc >array.c -o array && "/home/imsourobh/Documents/codes/c/cse/"array zsh: segmentation fault "/home/imsourobh/Documents/codes>c/cse/"array
Your problem is that the
nvariable is uninitialized. This means it's value is undefined, and using it to index an array is undefined behavior. Undefined behavior means anything can happen. Your program might have worked exactly as you planned.Or you might have gotten a segfault, which is what actually did happen.
To avoid this,
nshould have been initialized to0.As a sidenote, since
n++returns the value ofn, then increments it, you could save yourself a line of code:Or you might avoid the need for
nat all by using some math. Here I've defined constants for the dimensions of your two-dimensional array. I've also locally scopedrandcto their respective loops as they aren't needed outside of that scope. Lastly, I've usedsize_trather thanint.