简体   繁体   English

当我声明一个矩阵时,为什么这个数组会出错?

[英]Why is this array bugging when I declare a matrix?

That's the code:那是代码:

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

int main()
{
    int linhas=0, col=0, num=0, i=0, pos1[100];
    int pos[100];
    scanf("%d %d %d", &linhas, &col, &num);

    int matriz[linhas][col];

    for(i=0; i<num;i++){
       scanf(" %c%d", &pos[i], &pos1[i]);
    }

    for(i=0;i<num;i++){
        pos[i] -= 97;
    }

    return 0;
}

It's quite simple, I declared 2 arrays, one to store the value of a char( pos[] ), and the other to store integer values( pos1[] ), and it works:D.这很简单,我声明了 2 个数组,一个用于存储 char( pos[] ) 的值,另一个用于存储整数值 ( pos1[] ),它可以工作:D。

The thing is, if I declare a matrix ex: matrix[linhas][col] , my code does not really store the values of a char, and if I take it off, it starts to store normally, also, it does not matter whether if I declare the matrix right after getting the rows and colums (linhas and col) or if I declare it at the end of the code.问题是,如果我声明一个矩阵 ex: matrix[linhas][col] ,我的代码并没有真正存储一个字符的值,如果我取下它,它会开始正常存储,也没关系无论是在获取行和列(linhas 和 col)之后立即声明矩阵,还是在代码末尾声明它。 I don't know what the problem is, and I'd appreciate any hints.我不知道问题是什么,我很感激任何提示。

    int pos[100];
    scanf("%d %d %d", &linhas, &col, &num);

    int matriz[linhas][col];

    for(i=0; i<num;i++){
       scanf(" %c%d", &pos[i], &pos1[i]);
    }

The %c format specifier will read in a character, but it requires the address of a character to read it into. %c格式说明符将读入一个字符,但它需要一个字符的地址来读入。 You pass it the address of an int.你将一个int的地址传递给它。

The simplest fix is to change pos to char pos[100];最简单的解决方法是将pos更改为char pos[100]; . . Another possible fix is this:另一个可能的解决方法是:

    for(i=0; i<num;i++){
       char c;
       scanf(" %c%d", &c, &pos1[i]);
       pos[i] = c;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么当我在 C 中声明一个维度为 0 的矩阵时不会引发错误? - Why no error is raised when I declare a matrix that has 0 as a dimension in C? 为什么我不能在不声明像const这样的矩阵的情况下进行编译 - Why i can't compile without declare a matrix like const 为什么在我声明testArray [] = {&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;}时将49、50、51、52存储在数组中? (C程序设计) - Why is 49, 50, 51, 52 stored in the array when I declare testArray[] = {'1','2','3','4','5'}? (C programming) 为什么我不能在IF-Else中声明char数组? - Why Can't I declare char array in IF-Else? 为什么在声明另一个变量时此代码崩溃? - Why does this code crash when I declare one more variable? 为什么当我声明这两个变量时我的程序崩溃了? - Why my program crashes when I declare this two variables? 为什么在Win32中使用`GetAsyncKeyState()`时我的热键会出错? - Why are my hotkeys bugging out when using `GetAsyncKeyState()` in Win32? 我的程序只在我声明一个额外的数组时才有效 - My program only works when I declare an extra array 当我在 C 语言的结构中声明数组时会发生什么? - What happens when I declare an array in a struct in C language? 声明2数组时堆栈溢出 - Stack overflow when declare 2 array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM