首页 \ 问答 \ 矩阵分段故障(Matrix Segmentation Fault)

矩阵分段故障(Matrix Segmentation Fault)

我正在尝试编写一个计算nXn矩阵行列式的代码。 对于3x3矩阵,代码运行良好,但在4X4矩阵或更大的矩阵上程序崩溃。 你能告诉我我做错了什么吗?

#include<stdio.h>
#include<stdlib.h>

double sum(int n, double **matrix);

int main(){

    double row, col, size;

    int i,j,k;

    FILE *fd=fopen("input10.txt","r");

    fscanf(fd,"%lf", &size);

    row = size;
    col = size;

        double ** matrix=(double **) malloc (row*sizeof (double*));

        if(matrix != NULL){
            for(k=0; k<row ;k++){
                matrix[k]=(double*) calloc (col,sizeof (double));
        }
    }


    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            fscanf(fd,"%lf",&matrix[i][j]);

        }
    }
    printf("%.2le",sum(size,matrix));  

    return 0;
}

double computeDeterminant(unsigned char end, unsigned char start, double **matrix)
{
    int i,j,k;
    double s=0;

    double row, col;
    row = end;
    col = end;
    double ** b=(double **) malloc (row*sizeof (double*));

        if(matrix != NULL){
            for(k=0; k<row ;k++){
                b[k]=(double*) calloc (col,sizeof (double));
        }
    }


    for(i=0;i<end;i++){
        for(j=0;j<end;j++){     
            b[i][j]=matrix[i][j];
        }
    }

    for(i=0;i<end-1;i++){   
        for(j=1;j<=end;j++){
            b[i][j]=b[i+1][j];
        }
    }


    for(i=0;i<end-1;i++){
        for(j=start;j<=end-1;j++){
            b[i][j]=b[i][j+1];
        }
    }


    if (end-1==2){
        return b[1][1]*b[2][2]-b[1][2]*b[2][1];
    }
    else{
        for (j=0;j<end-1;j++){
            s=s+pw(1+j)*b[1][j]*computeDeterminant(end-1,j,b);
        }return s;
    }
}

double sum(int n,double **matrix)
{
    int j;
    double s=0;

    if(n>2)
    {
        for(j=1;j<=n;j++)
            s=s+pw(1+j)*matrix[1][j]*computeDeterminant(n, j, matrix);
        return s;
    }
    else
        return matrix[1][1]*matrix[2][2]-matrix[1][2]*matrix[2][1];
}

int pw(int y)
{
     return (y%2)==0?1:-1; 
}

I am trying to write a code that calculates the determinant for an nXn matrix. For a 3x3 matrix the code works well, but on a 4X4 matrix or bigger the program crashes. Can you tell me what I am doing wrong?

#include<stdio.h>
#include<stdlib.h>

double sum(int n, double **matrix);

int main(){

    double row, col, size;

    int i,j,k;

    FILE *fd=fopen("input10.txt","r");

    fscanf(fd,"%lf", &size);

    row = size;
    col = size;

        double ** matrix=(double **) malloc (row*sizeof (double*));

        if(matrix != NULL){
            for(k=0; k<row ;k++){
                matrix[k]=(double*) calloc (col,sizeof (double));
        }
    }


    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            fscanf(fd,"%lf",&matrix[i][j]);

        }
    }
    printf("%.2le",sum(size,matrix));  

    return 0;
}

double computeDeterminant(unsigned char end, unsigned char start, double **matrix)
{
    int i,j,k;
    double s=0;

    double row, col;
    row = end;
    col = end;
    double ** b=(double **) malloc (row*sizeof (double*));

        if(matrix != NULL){
            for(k=0; k<row ;k++){
                b[k]=(double*) calloc (col,sizeof (double));
        }
    }


    for(i=0;i<end;i++){
        for(j=0;j<end;j++){     
            b[i][j]=matrix[i][j];
        }
    }

    for(i=0;i<end-1;i++){   
        for(j=1;j<=end;j++){
            b[i][j]=b[i+1][j];
        }
    }


    for(i=0;i<end-1;i++){
        for(j=start;j<=end-1;j++){
            b[i][j]=b[i][j+1];
        }
    }


    if (end-1==2){
        return b[1][1]*b[2][2]-b[1][2]*b[2][1];
    }
    else{
        for (j=0;j<end-1;j++){
            s=s+pw(1+j)*b[1][j]*computeDeterminant(end-1,j,b);
        }return s;
    }
}

double sum(int n,double **matrix)
{
    int j;
    double s=0;

    if(n>2)
    {
        for(j=1;j<=n;j++)
            s=s+pw(1+j)*matrix[1][j]*computeDeterminant(n, j, matrix);
        return s;
    }
    else
        return matrix[1][1]*matrix[2][2]-matrix[1][2]*matrix[2][1];
}

int pw(int y)
{
     return (y%2)==0?1:-1; 
}

原文:https://stackoverflow.com/questions/34534221
更新时间:2022-08-13 22:08

最满意答案

从Swift文档中的“语句”

退货声明

return语句出现在函数或方法定义的主体中,并导致程序执行返回到调用函数或方法。

警卫声明

如果不满足一个或多个条件,则使用guard语句将程序控制转移到范围之外。
...
保护语句的else子句是必需的,并且必须调用标有noreturn属性的函数或者在guard语句的封闭范围之外传递程序控制...

如果你的guard let details = condition失败,那么从当前函数return “立即”返回。 您不能简单地继续,因为details将是未定义的。 这正是guard声明所做的。

您可以通过引入本地范围来解决您的问题:

print("Before details Check")
checkLabel: do {
    guard let details = result where details.isKindOfClass(NSArray) else {
        break checkLabel
    }
    print("Returned Result \(details)")
}
print("After details Check")

这里,如果条件失败, break checkLabeldo -scope之后继续执行。

但更简单的方法是使用if-let而不是guard-let

print("Before details Check")
if let details = result where details.isKindOfClass(NSArray) {
    print("Returned Result \(details)")
}
print("After details Check")

From "Statements" in the Swift documentation:

Return Statement

A return statement occurs in the body of a function or method definition and causes program execution to return to the calling function or method.

and

Guard Statement

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
...
The else clause of a guard statement is required, and must either call a function marked with the noreturn attribute or transfer program control outside the guard statement’s enclosing scope ...

If your guard let details = condition fails then return "immediately" returns from the current function. You cannot simply continue because details would be undefined. That is exactly what the guard statement is made for.

You could solve your problem by introducing a local scope:

print("Before details Check")
checkLabel: do {
    guard let details = result where details.isKindOfClass(NSArray) else {
        break checkLabel
    }
    print("Returned Result \(details)")
}
print("After details Check")

Here, break checkLabel continues execution after the do-scope if the condition failed.

But a much simpler way would be to use if-let instead of guard-let:

print("Before details Check")
if let details = result where details.isKindOfClass(NSArray) {
    print("Returned Result \(details)")
}
print("After details Check")

相关问答

更多
  • 你正在防止名称==“汉斯”的情况 将您的反向更改为防护装置内部,并且打印件应替换为反向装置 You are guarding AGAINST the case where name == "Hans" Change your reverse to be inside the guard, and the print should replace the reverse
  • 完全可以做你想象的事情,它恰好不是那个特定的代码所做的。 return总是退出一个方法,而不是本地范围。 要做你想做的事,你可以使用标签,并break : func testGuardControlFlow () { let x = 2 let y = 2 func embededFunc () { breakLabel: if y == 2 { guard x == 1 else { p ...
  • 根据我的经验和其他人' 是,它不是解析和读取花费时间的文件,而是各种优化和代码生成过程 因此,打开一个文件来解析inlucde防护对于大型项目的构建时间应该可以忽略不计。 我的意思是它不能成为程序的瓶颈 ! 因此,选择你喜欢的风格,它真的是基于意见。 这里发现另一个有趣的评论 有一次,可能有一两个编译器愚蠢到每次打开文件来检查包含警卫。 在这个千年中没有编制的编译器会这样做,因为它可以只保留一个文件表并包含警卫并在打开文件之前查阅。 阅读更多文件范围的包含警卫 。 From my experience an ...
  • 你在这里犯了一些错误 请求url和方法的检查应该在supports方法中。 您正在寻找标题而不是您的supports方法中的请求变量。 将其替换为以下内容。 public function supports(Request $request) : ?bool { return $request->request->has('_username') && $request->request->has('_password'); } You have made a few mistake here T ...
  • canActivate函数必须返回布尔值,布尔值的承诺或布尔值的可观察值。 在你的情况下,你什么都没有返回。 可能是因为你忽略了你的功能的return 。 但是如果你添加它,它将不起作用,因为那样你将返回一个订阅,而这个订阅不被签名所接受。 你可以做的是这样的: canActivate() { return this.authService.loggedIn().map(res => { if(!res) { this.router.navigate(['/login']); ...
  • 我确信,我开始的方式是正确的。 我发现这篇文章对函数的未命名参数,C ++或多或少证实了我。 现在,我删除了参数名称,它实现如下: auto foo( std::lock_guard & ) -> void { ... } 我觉得它更优雅,因为它不使用gcc扩展,它是完全C ++兼容的。 I am convinced, the way I started was correct. I found this post On unnamed parameters to funct ...
  • 从Swift文档中的“语句” : 退货声明 return语句出现在函数或方法定义的主体中,并导致程序执行返回到调用函数或方法。 和 警卫声明 如果不满足一个或多个条件,则使用guard语句将程序控制转移到范围之外。 ... 保护语句的else子句是必需的,并且必须调用标有noreturn属性的函数或者在guard语句的封闭范围之外传递程序控制... 如果你的guard let details = condition失败,那么从当前函数return “立即”返回。 您不能简单地继续,因为details将是未定 ...
  • 这应该有效,但我相信守卫是按顺序并行执行的。 所以第二个不会等到第一个返回一个值。 如果您的警卫是同步的,这不应该真正影响您,但如果它们是异步的,您将遇到这个“问题”。 如果你需要你的警卫相互依赖,你可以将支票的共同部分分开,你的所有警卫都可以称之为逻辑。 但我认为在大多数情况下甚至不需要这样做,因为如果只有其中一个失败,则路线不会被激活。 This should work but I believe the guards are executed in parallel not in a sequence ...
  • 我得到rubocop错误使用一个保护条款而不是if-else语句...... 最好的方法是什么 ? 首先要仔细阅读关于什么保护条款的文章。 以下是重构使用guard子句的方法: def self.get_image(product_id) initialize product_id = product_id.to_s return cache_image(product_id) unless @image_db.key?(product_id) return @image_d ...
  • 不可能。 要使用类中其他变量的知识来实例化变量,可以使用延迟初始化或getter。 var testString : String? lazy var testString2 : String = { guard let t = self.testString else { return String()} return t }() 如果我错了,请随意纠正我:) 保护是为了我认为的功能的稳健性,并且如果条件错误将在功能中休息。 因此,如果你真的需要这个变量,它必须满足条件。 就像一个 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)