Segmentation fault in passing multidimensional arrays to functions in C
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
We saw passing arrays to functions using pointers in my intro. to C class, and I'm trying to learn how to pass multidimensional arrays on my own. I tried writing a function to assign the values of the entries of a matrix onto a local array, but I get a segmentation fault. I was hoping someone could explain why this happens and how to fix it. I'm using the terminal on macOS Sierra. Thanks in advance. My code is below:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix();
int main(void){
int rows, cols;
printf("nEnter the number of columns:n");
scanf("%d", &cols);
printf("nEnter the number of rows:n");
scanf("%d", &rows);
int matrix[rows][cols];
fillMatrix(&matrix[rows][cols], rows, cols);
for (int i = 0; i < rows; ++i){
for (int j = 0; j < (cols - 1); ++j){
printf("%d ", matrix[i][j]);
} printf("%dn", matrix[i][(cols -1)]);
}
return 0;
}
void fillMatrix( int *matrix, int rows, int cols ){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
printf("nPlease enter the A(%d,%d) entry:n", i, j);
scanf("%d", &*(matrix + (i*cols) + j));
}
}
return;
}
c macos segmentation-fault
add a comment |
We saw passing arrays to functions using pointers in my intro. to C class, and I'm trying to learn how to pass multidimensional arrays on my own. I tried writing a function to assign the values of the entries of a matrix onto a local array, but I get a segmentation fault. I was hoping someone could explain why this happens and how to fix it. I'm using the terminal on macOS Sierra. Thanks in advance. My code is below:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix();
int main(void){
int rows, cols;
printf("nEnter the number of columns:n");
scanf("%d", &cols);
printf("nEnter the number of rows:n");
scanf("%d", &rows);
int matrix[rows][cols];
fillMatrix(&matrix[rows][cols], rows, cols);
for (int i = 0; i < rows; ++i){
for (int j = 0; j < (cols - 1); ++j){
printf("%d ", matrix[i][j]);
} printf("%dn", matrix[i][(cols -1)]);
}
return 0;
}
void fillMatrix( int *matrix, int rows, int cols ){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
printf("nPlease enter the A(%d,%d) entry:n", i, j);
scanf("%d", &*(matrix + (i*cols) + j));
}
}
return;
}
c macos segmentation-fault
add a comment |
We saw passing arrays to functions using pointers in my intro. to C class, and I'm trying to learn how to pass multidimensional arrays on my own. I tried writing a function to assign the values of the entries of a matrix onto a local array, but I get a segmentation fault. I was hoping someone could explain why this happens and how to fix it. I'm using the terminal on macOS Sierra. Thanks in advance. My code is below:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix();
int main(void){
int rows, cols;
printf("nEnter the number of columns:n");
scanf("%d", &cols);
printf("nEnter the number of rows:n");
scanf("%d", &rows);
int matrix[rows][cols];
fillMatrix(&matrix[rows][cols], rows, cols);
for (int i = 0; i < rows; ++i){
for (int j = 0; j < (cols - 1); ++j){
printf("%d ", matrix[i][j]);
} printf("%dn", matrix[i][(cols -1)]);
}
return 0;
}
void fillMatrix( int *matrix, int rows, int cols ){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
printf("nPlease enter the A(%d,%d) entry:n", i, j);
scanf("%d", &*(matrix + (i*cols) + j));
}
}
return;
}
c macos segmentation-fault
We saw passing arrays to functions using pointers in my intro. to C class, and I'm trying to learn how to pass multidimensional arrays on my own. I tried writing a function to assign the values of the entries of a matrix onto a local array, but I get a segmentation fault. I was hoping someone could explain why this happens and how to fix it. I'm using the terminal on macOS Sierra. Thanks in advance. My code is below:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix();
int main(void){
int rows, cols;
printf("nEnter the number of columns:n");
scanf("%d", &cols);
printf("nEnter the number of rows:n");
scanf("%d", &rows);
int matrix[rows][cols];
fillMatrix(&matrix[rows][cols], rows, cols);
for (int i = 0; i < rows; ++i){
for (int j = 0; j < (cols - 1); ++j){
printf("%d ", matrix[i][j]);
} printf("%dn", matrix[i][(cols -1)]);
}
return 0;
}
void fillMatrix( int *matrix, int rows, int cols ){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
printf("nPlease enter the A(%d,%d) entry:n", i, j);
scanf("%d", &*(matrix + (i*cols) + j));
}
}
return;
}
c macos segmentation-fault
c macos segmentation-fault
asked Nov 17 '18 at 0:59
Alex DAlex D
1245
1245
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
Given the declaration
int matrix[rows][cols];
This code is wrong:
fillMatrix(&matrix[rows][cols], rows, cols);
The address of &matrix[rows][cols]
is past the end of the matrix.
The first element of the matrix is &matrix[0][0]
, and the last element of the matrix is &matrix[rows-1][cols-1]
.
Also, this declaration
void fillMatrix();
will cause problems with this defintion:
void fillMatrix( int *matrix, int rows, int cols ){
...
They need to match. Right now, because of the void fillMatrix()
declaration up top, arguments get passed to the function via default argument promotion, but because the definition has explicit arguments, the function itself expects the arguments to be passed as int *
or int
. You're probably not having problems with that as the defaults for those arguments are likely the same as those arguments, but function definitions and declarations generally must match exactly.
I haven't examined your code for other issues.
Thank you this fixed it! I'm guilty of copy-pasting without thinking about it or checking twice. "You can accept an answer in seven minutes"
– Alex D
Nov 17 '18 at 1:07
@AlexD I noticed something else, too. Your function definition and declaration don't match forfillMatrix()
.
– Andrew Henle
Nov 17 '18 at 1:12
add a comment |
In C when you are declaring an array you need to specify its size at the time of compilation. When you decelerate the array in line
int matrix[rows][cols];
You actually initialise its size with rubbish values. In case of my compiler it was initialised with size of [0][0]. In order to achieve what you want you need to do one of two things:
- Specify explicitly what is the size of the array before compilation
- Dynamically allocate space for the array
"you need to specify its size at the time of compilation" -- not true since C99 with the addition of variable length arrays, which are sized at runtime (though these were made optional again with C11, VLAs are still available almost everywhere). Also,rows
andcols
don't have garbage values in OP code unless the user input is bad (so OP should validate the input before using it to avoid undefined behavior.)
– David Bowling
Nov 17 '18 at 1:25
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347241%2fsegmentation-fault-in-passing-multidimensional-arrays-to-functions-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Given the declaration
int matrix[rows][cols];
This code is wrong:
fillMatrix(&matrix[rows][cols], rows, cols);
The address of &matrix[rows][cols]
is past the end of the matrix.
The first element of the matrix is &matrix[0][0]
, and the last element of the matrix is &matrix[rows-1][cols-1]
.
Also, this declaration
void fillMatrix();
will cause problems with this defintion:
void fillMatrix( int *matrix, int rows, int cols ){
...
They need to match. Right now, because of the void fillMatrix()
declaration up top, arguments get passed to the function via default argument promotion, but because the definition has explicit arguments, the function itself expects the arguments to be passed as int *
or int
. You're probably not having problems with that as the defaults for those arguments are likely the same as those arguments, but function definitions and declarations generally must match exactly.
I haven't examined your code for other issues.
Thank you this fixed it! I'm guilty of copy-pasting without thinking about it or checking twice. "You can accept an answer in seven minutes"
– Alex D
Nov 17 '18 at 1:07
@AlexD I noticed something else, too. Your function definition and declaration don't match forfillMatrix()
.
– Andrew Henle
Nov 17 '18 at 1:12
add a comment |
Given the declaration
int matrix[rows][cols];
This code is wrong:
fillMatrix(&matrix[rows][cols], rows, cols);
The address of &matrix[rows][cols]
is past the end of the matrix.
The first element of the matrix is &matrix[0][0]
, and the last element of the matrix is &matrix[rows-1][cols-1]
.
Also, this declaration
void fillMatrix();
will cause problems with this defintion:
void fillMatrix( int *matrix, int rows, int cols ){
...
They need to match. Right now, because of the void fillMatrix()
declaration up top, arguments get passed to the function via default argument promotion, but because the definition has explicit arguments, the function itself expects the arguments to be passed as int *
or int
. You're probably not having problems with that as the defaults for those arguments are likely the same as those arguments, but function definitions and declarations generally must match exactly.
I haven't examined your code for other issues.
Thank you this fixed it! I'm guilty of copy-pasting without thinking about it or checking twice. "You can accept an answer in seven minutes"
– Alex D
Nov 17 '18 at 1:07
@AlexD I noticed something else, too. Your function definition and declaration don't match forfillMatrix()
.
– Andrew Henle
Nov 17 '18 at 1:12
add a comment |
Given the declaration
int matrix[rows][cols];
This code is wrong:
fillMatrix(&matrix[rows][cols], rows, cols);
The address of &matrix[rows][cols]
is past the end of the matrix.
The first element of the matrix is &matrix[0][0]
, and the last element of the matrix is &matrix[rows-1][cols-1]
.
Also, this declaration
void fillMatrix();
will cause problems with this defintion:
void fillMatrix( int *matrix, int rows, int cols ){
...
They need to match. Right now, because of the void fillMatrix()
declaration up top, arguments get passed to the function via default argument promotion, but because the definition has explicit arguments, the function itself expects the arguments to be passed as int *
or int
. You're probably not having problems with that as the defaults for those arguments are likely the same as those arguments, but function definitions and declarations generally must match exactly.
I haven't examined your code for other issues.
Given the declaration
int matrix[rows][cols];
This code is wrong:
fillMatrix(&matrix[rows][cols], rows, cols);
The address of &matrix[rows][cols]
is past the end of the matrix.
The first element of the matrix is &matrix[0][0]
, and the last element of the matrix is &matrix[rows-1][cols-1]
.
Also, this declaration
void fillMatrix();
will cause problems with this defintion:
void fillMatrix( int *matrix, int rows, int cols ){
...
They need to match. Right now, because of the void fillMatrix()
declaration up top, arguments get passed to the function via default argument promotion, but because the definition has explicit arguments, the function itself expects the arguments to be passed as int *
or int
. You're probably not having problems with that as the defaults for those arguments are likely the same as those arguments, but function definitions and declarations generally must match exactly.
I haven't examined your code for other issues.
edited Nov 17 '18 at 1:10
answered Nov 17 '18 at 1:05
Andrew HenleAndrew Henle
20.8k31535
20.8k31535
Thank you this fixed it! I'm guilty of copy-pasting without thinking about it or checking twice. "You can accept an answer in seven minutes"
– Alex D
Nov 17 '18 at 1:07
@AlexD I noticed something else, too. Your function definition and declaration don't match forfillMatrix()
.
– Andrew Henle
Nov 17 '18 at 1:12
add a comment |
Thank you this fixed it! I'm guilty of copy-pasting without thinking about it or checking twice. "You can accept an answer in seven minutes"
– Alex D
Nov 17 '18 at 1:07
@AlexD I noticed something else, too. Your function definition and declaration don't match forfillMatrix()
.
– Andrew Henle
Nov 17 '18 at 1:12
Thank you this fixed it! I'm guilty of copy-pasting without thinking about it or checking twice. "You can accept an answer in seven minutes"
– Alex D
Nov 17 '18 at 1:07
Thank you this fixed it! I'm guilty of copy-pasting without thinking about it or checking twice. "You can accept an answer in seven minutes"
– Alex D
Nov 17 '18 at 1:07
@AlexD I noticed something else, too. Your function definition and declaration don't match for
fillMatrix()
.– Andrew Henle
Nov 17 '18 at 1:12
@AlexD I noticed something else, too. Your function definition and declaration don't match for
fillMatrix()
.– Andrew Henle
Nov 17 '18 at 1:12
add a comment |
In C when you are declaring an array you need to specify its size at the time of compilation. When you decelerate the array in line
int matrix[rows][cols];
You actually initialise its size with rubbish values. In case of my compiler it was initialised with size of [0][0]. In order to achieve what you want you need to do one of two things:
- Specify explicitly what is the size of the array before compilation
- Dynamically allocate space for the array
"you need to specify its size at the time of compilation" -- not true since C99 with the addition of variable length arrays, which are sized at runtime (though these were made optional again with C11, VLAs are still available almost everywhere). Also,rows
andcols
don't have garbage values in OP code unless the user input is bad (so OP should validate the input before using it to avoid undefined behavior.)
– David Bowling
Nov 17 '18 at 1:25
add a comment |
In C when you are declaring an array you need to specify its size at the time of compilation. When you decelerate the array in line
int matrix[rows][cols];
You actually initialise its size with rubbish values. In case of my compiler it was initialised with size of [0][0]. In order to achieve what you want you need to do one of two things:
- Specify explicitly what is the size of the array before compilation
- Dynamically allocate space for the array
"you need to specify its size at the time of compilation" -- not true since C99 with the addition of variable length arrays, which are sized at runtime (though these were made optional again with C11, VLAs are still available almost everywhere). Also,rows
andcols
don't have garbage values in OP code unless the user input is bad (so OP should validate the input before using it to avoid undefined behavior.)
– David Bowling
Nov 17 '18 at 1:25
add a comment |
In C when you are declaring an array you need to specify its size at the time of compilation. When you decelerate the array in line
int matrix[rows][cols];
You actually initialise its size with rubbish values. In case of my compiler it was initialised with size of [0][0]. In order to achieve what you want you need to do one of two things:
- Specify explicitly what is the size of the array before compilation
- Dynamically allocate space for the array
In C when you are declaring an array you need to specify its size at the time of compilation. When you decelerate the array in line
int matrix[rows][cols];
You actually initialise its size with rubbish values. In case of my compiler it was initialised with size of [0][0]. In order to achieve what you want you need to do one of two things:
- Specify explicitly what is the size of the array before compilation
- Dynamically allocate space for the array
answered Nov 17 '18 at 1:19
Mateusz StompórMateusz Stompór
11716
11716
"you need to specify its size at the time of compilation" -- not true since C99 with the addition of variable length arrays, which are sized at runtime (though these were made optional again with C11, VLAs are still available almost everywhere). Also,rows
andcols
don't have garbage values in OP code unless the user input is bad (so OP should validate the input before using it to avoid undefined behavior.)
– David Bowling
Nov 17 '18 at 1:25
add a comment |
"you need to specify its size at the time of compilation" -- not true since C99 with the addition of variable length arrays, which are sized at runtime (though these were made optional again with C11, VLAs are still available almost everywhere). Also,rows
andcols
don't have garbage values in OP code unless the user input is bad (so OP should validate the input before using it to avoid undefined behavior.)
– David Bowling
Nov 17 '18 at 1:25
"you need to specify its size at the time of compilation" -- not true since C99 with the addition of variable length arrays, which are sized at runtime (though these were made optional again with C11, VLAs are still available almost everywhere). Also,
rows
and cols
don't have garbage values in OP code unless the user input is bad (so OP should validate the input before using it to avoid undefined behavior.)– David Bowling
Nov 17 '18 at 1:25
"you need to specify its size at the time of compilation" -- not true since C99 with the addition of variable length arrays, which are sized at runtime (though these were made optional again with C11, VLAs are still available almost everywhere). Also,
rows
and cols
don't have garbage values in OP code unless the user input is bad (so OP should validate the input before using it to avoid undefined behavior.)– David Bowling
Nov 17 '18 at 1:25
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347241%2fsegmentation-fault-in-passing-multidimensional-arrays-to-functions-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown