【问题标题】:print result using system calls使用系统调用打印结果
【发布时间】:2016-10-22 18:44:37
【问题描述】:

对于我的操作系统类,我需要仅使用系统调用打印出此矩阵乘法的结果。在我的讲义之后,我写了这段代码。我用:

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

#define N 1000

// Matrix 
long long int A[N][N],B[N][N],R[N][N];

int main(int argc, char *argv[])
{
int x,y,z;
char str[100];

/* Matrix inicialization */
for(y=0;y<N;y++) 
    for(x=0;x<N;x++)
    {
        A[y][x]=x;
        B[y][x]=y;
        R[y][x]=0;  
    }

/* Matrix multiplication */
for(y=0;y<N;y++)
    for(z=0;z<N;z++) 
        for(x=0;x<N;x++) 
        {
            R[y][x]+= A[y][z] * B[z][x];    
        }


//System calls for printing the result 
sprintf(str,"%lld\n",R);
write(1,str,strlen(str));       

exit(0);
}

现在,它正在控制台中打印一个 14295680。教授给了我们一个机器码文件,打印的是332833500,这似乎更合理。

提前致谢。

编辑:在 printf 调用中更改了类型 Edit2:修复 R[N][N]

【问题讨论】:

  • sprintf() 不是系统调用。是库函数。更不用说它真的很不安全。
  • R[N][N] 不存在。
  • 您在传递long long int 时使用了浮点格式说明符。这是未定义的行为。
  • 您无法按照您尝试的方式打印出RRlong long ints 的二维数组。

标签: c linux system-calls


【解决方案1】:

只需替换 sprintf 值:

sprintf(str,"%lld\n",R[N-1][N-1]); // = 332833500
write(1,str,strlen(str));       

而不是

sprintf(str,"%lld\n",R); // this is a pointer
write(1,str,strlen(str));       

【讨论】:

    猜你喜欢
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多