gpt4 book ai didi

c - 数组值发生变化

转载 作者:行者123 更新时间:2023-11-30 15:58:29 25 4
gpt4 key购买 nike

所以我有两个问题:

我正在使用 netbeans 来编写此代码。

首先是我在 c.sArr 中设置的数组值从 7 更改为某个随机数,但我不明白为什么。

第二个是,当我尝试在 netbeans 中运行调试时,代码会给出一个段错误,而当我正常运行它时却不会。它在 atoi 函数中出现段错误。

这是怎么回事?

#include <stdio.h>
#include <stdlib.h>
#include "spoonMatrix.c"

int main(int argc, char** argv) {
int iterations;
int argCounter = 0;
int debug = 1;
int i,j,q;

if(argc < 2)
return -1;

if(debug == 1){
for(q=0;q<argc;q++)
printf("%s\n", argv[argCounter++]); //Checking the params
}

argCounter = 1;
iterations = atoi(argv[argCounter++]);

if(debug == 1)
printf("%d", iterations);

for(i=0;i<iterations;i++){
int rows = 0;
int columns = 0;
int m = 0, n, p, elemCount;
int posCount = 0;
int temp;
cm c;
c.row = rows;
c.column = columns;
c.elems = (char*)calloc(rows*columns, sizeof(char));
c.sArr = (int*)calloc(rows*columns, sizeof(int));

rows = atoi(argv[argCounter++]);
columns = atoi(argv[argCounter++]);

for(m=0;m<rows*columns;m++)
{
c.sArr[m] = -2;
//printf("Here");
}

if(debug == 1)
{
printf("Rows : Columns - %d : %d\n", rows, columns);
}

temp = argCounter;
printf("argCounter is: %d\n", argCounter);
for(elemCount = 0 ; argCounter < temp + rows; argCounter++)
{
for(n=0; n<columns; n++, elemCount++)
{
c.elems[elemCount] = argv[argCounter][n];
//if(debug == 1)
// printf("%c\t", c.elems[elemCount]);
if(c.elems[elemCount]== 's' || c.elems[elemCount] == 'S')
{
c.sArr[posCount] = elemCount;
printf("%c\t%d\t%d\t%d\n", c.elems[elemCount], elemCount, c.sArr[posCount++], posCount);

}
}
}

printf("%d\n", c.sArr[0]);
if(debug == 1)
{
for(j=0; j<rows*columns; j++)
{
printf("%c ", c.elems[j]);
}

printf("\n");

for(j=0;j<rows*columns;j++)
{
printf("%d ", c.sArr[j]);
}
}
}

return (EXIT_SUCCESS);
}

另一个文件是:

struct charMat{
int row;
int column;
char* elems;
int* sArr;
};

typedef struct charMat cm;

匆忙编码,请原谅奇怪的调试语句。

谢谢

最佳答案

您没有分配(足够的)内存:

int rows = 0;
int columns = 0;

c.elems = (char*)calloc(rows*columns, sizeof(char)); // rows * columns is 0
c.sArr = (int*)calloc(rows*columns, sizeof(int)); // rows * columns is 0

rows = atoi(argv[argCounter++]);
columns = atoi(argv[argCounter++]);

来自 calloc:

If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer.

关于c - 数组值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9702055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com