[英]How do I put multiple integers into int* tab; in two different loops separated by 0 eg. [1,1,1,0,1,1] in VS 2019 in C
I am writing a emulator for Turing machine subtraction and, to start, I need to have the m
and n
converted into 1s and one 0s.我正在为图灵机减法编写一个模拟器,首先,我需要将m
和n
转换为 1 和一个 0。 For example, if m = 3
, n = 2
, the output would be [1,1,1,0,1,1]
in the int
array.例如,如果m = 3
, n = 2
,则 output 在int
数组中将是[1,1,1,0,1,1]
。
I tried using malloc
to allocate memory for int* tab
and, after that, I simply put the first ones in the first loop, then append a 0, then, in another loop, I'm adding the n
1s.我尝试使用malloc
为int* tab
分配 memory,然后,我简单地将第一个放在第一个循环中,然后n
在另一个循环中添加 0,然后在另一个循环中。
The problem is with Visual Studio, I think, because I tried the same code in vim and the output was correct.我认为问题出在 Visual Studio 上,因为我在 vim 中尝试了相同的代码,而 output 是正确的。 In VS, the output of 1s is correct but, instead of 0, I get some random negative number.在 VS 中,1s 的 output 是正确的,但是我得到的不是 0,而是一些随机负数。
Here's the code:这是代码:
scanf_s("%d", &m);
printf("n = ");
scanf_s("%d", &n);
int* tab = malloc(sizeof(int) * (n + m + 1));
int i;
for (i = 0; i < m; i++)
{
tab[i] = 1;
}
tab[i + 1] = 0;
int j = 0;
for (j = i + 1; j < n + i + 1; j++)
{
tab[j] = 1;
}
for (int k = 0; k < n + m + 1; k++)
{
printf("%d", tab[k]);
}
I believe我相信
tab[i + 1] = 0;
is the problem.是问题所在。 From previous loop execution the control will only come out when i<m
is false, ie, for the case when i == m
, as per the increment statement.从之前的循环执行中,控制只会在i<m
为假时出现,即,对于i == m
的情况,根据增量语句。
Now, you want to put the 0
at this index, not at index + 1
.现在,你想把0
放在这个索引上,而不是放在index + 1
上。
Change to tab[i] = 0;
更改为tab[i] = 0;
. .
Now, the probable reason for the negative number: The content of the memory location returned by malloc()
is indeterminate, so if you miss to write the index when i == m
(you were writing from 0
to m-1
, then from m+1
to m+n-1
), while reading it'll return that indeterminate value.现在,负数的可能原因: malloc()
返回的 memory 位置的内容是不确定的,所以如果您在i == m
时错过写入索引(您从0
写入m-1
,然后从m+1
到m+n-1
),在读取它时会返回那个不确定的值。
The problem is in your tab[i + 1] = 0;
问题出在你的tab[i + 1] = 0;
line.线。 When the preceding loop has finished, then i
will be equal to m
— that is to say, the i
value will already be "one beyond the end".当前面的循环结束时, i
将等于m
也就是说, i
的值已经是“结束后的一个”。
So, just change that to: tab[i] = 0;
因此,只需将其更改为: tab[i] = 0;
and you should be fine.你应该没事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.