简体   繁体   English

二维数组打印方式错误

[英]2D array is printing the wrong way

I'm creating a 2D dynamic array to keep track of transactions over several days.我正在创建一个二维动态数组来跟踪几天的交易。 I have created the 2D array and added the transactions.我已经创建了二维数组并添加了事务。 The problem is that is not printing the correct transactions.问题是没有打印正确的交易。 It will print correctly if I have the same amount of noOfdays and transcount.如果我有相同数量的 noOfdays 和 transcount,它将正确打印。 Ex 3 and 2. But it changes values if I have noOfdays 2 and trascount 3.例如 3 和 2。但如果我有 noOfdays 2 和 trascount 3,它会改变值。

Example output having noOfdays 2 and trascount 3.示例 output 具有 noOfdays 2 和 trascount 3。

在此处输入图像描述

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

int main(int argc, char const *argv[]) {

int noOfDays, transcount;
printf("Enter no of days:");
scanf("%d", &noOfDays);
printf("Enter total no of transaction:\n ");
scanf("%d", &transcount);
int *p= (int)malloc(noOfDays*transcount * sizeof(int));

int number = 0;
for (int i = 0; i < noOfDays; i++) {
  printf("Enter no of transaction per day:\n", i);
for (int j = 0; j < transcount; j++) {
  scanf("%d", &number);
  p[i*noOfDays + j] = number;
 }

}

printf("%s\n", "#Printing your 2d array:" );
for (int i = 0; i < noOfDays; i++){
 for (int j = 0; j < transcount; j++){
  int number = p[i*noOfDays + j];
  printf("%d\t", number);
}
printf("\n");
}

return 0;
}

It's probably your index formula in p[i*noOfDays+j] is not correct.这可能是您在p[i*noOfDays+j]中的索引公式不正确。

Change it from p[i*noOfDays+j] to p[i*transcount+j] .将其从p[i*noOfDays+j]更改为p[i*transcount+j]

The reason is the i is the index of the current transaction group.原因是i是当前事务组的索引。 The j is the index of specific transaction in a day. j是一天中特定交易的指数。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM