[英]How to access data of dynamic array of `int` when passed as function parameter?
here in my code I'm trying to increment the value of a specific array index.在我的代码中,我试图增加特定数组索引的值。 The thing is when I increment it with ++
the value of it increments by 4 for some reason instead of 1. I believe the way I access the value of that index is wrong.问题是当我用++
增加它时,它的值由于某种原因增加了 4 而不是 1。我相信我访问该索引值的方式是错误的。
void updateData(char** usernames, int** userWins, int** userDraws, int** userDefeats,
int totalUsers,char username1[],char username2[],int whoIsWinner,char againstPC){
int i;
printf("Username: %s.\tWins: %d.\tDraws: %d.\tDefeats: %d.\n",
usernames[0],userWins[0],userDraws[0],userDefeats[0]);
userWins[0]++;
userDraws[0]++;
userDefeats[0]++;
printf("Username: %s.\tWins: %d.\tDraws: %d.\tDefeats: %d.\n",
usernames[0],userWins[0],userDraws[0],userDefeats[0]);
}
userWins,userDraws,userDefeats are dynamic int arrays. userWins、userDraws、userDefeats 是动态 int 数组。 I'm using ** because I want them passed by reference.我使用 ** 因为我希望它们通过引用传递。 Please ignore 5 last parameters of the function.请忽略该函数的最后 5 个参数。
EDIT: added declaration and function call编辑:添加声明和函数调用
int* userWins;
int* userDraws;
int* userDefeats;
userWins=(int*) malloc(sizeof(int)*totalUsers);
userDraws=(int*) malloc(sizeof(int)*totalUsers);
userDefeats=(int*) malloc(sizeof(int)*totalUsers);
updateData(usernames,userWins,userDraws,userDefeats,totalUsers,tempUsername1,
tempUsername2,tempWinner,againstPC);
Your function takes in a double pointer, which means that in order to get the value you would have to dereference it twice.您的函数接受一个双指针,这意味着为了获得该值,您必须两次取消引用它。 However, userWins[0]
dereferences userWins
once, and you get a pointer back.但是, userWins[0]
取消对userWins
引用一次,您会得到一个指针。 Then the ++
operator increments the value by the size of the pointer, which on your system is 4. If userWins
is an array, simply pass it in as int* userWins
.然后++
运算符将值增加指针的大小,在您的系统上是 4。如果userWins
是一个数组,只需将它作为int* userWins
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.