如何解决如果我没有在其他函数中打印某些值,则main中的C打印值会有所不同
我正在尝试打印数组中的值。在ascii()内部,我打印了值以检查这些值是否已正确传输到主函数中。我还设置了random_values,以便数组内的所有整数都在33到126之间。
一切看起来都很好,但是问题是,当我注释编写用于检查ascii()内部的零件代码时,main函数中的值会混乱。它给了我384、386、387之类的值。
我认为这是某种内存问题,但是我对内存和指针知之甚少。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
void random_values (int a[],int l) {
for (int i = 0; i < l; i++) {
a[i] = (rand() % 94 + 33);
}
}
void set_length () {
//generates random integer between 8 and 15 which is used as the length of the array[]
length = (rand() % 8 + 8);
}
int ascii (int **pass)
{
int array[length];
//for assigning random values to the array []
random_values(array,length);
//the printed output from the main fuction is different if I comment this part - random_values() don't work
for (int i = 0; i < length; i++)
{
printf("%d ",array[i]);
}
*pass = array;
return 0;
}
int main () {
//to prevent rand() from producing the same value every time
srand(time(NULL));
set_length();
int *password = malloc(sizeof(int) * length);
ascii(&password);
for (int i = 0; i < length; i++) {
printf("%d ",password[i]);
}
//just to check
printf("\nlength is %d",length);
printf("\n");
}
解决方法
您正在发送局部变量的指针。 我将ascii函数更改为:
int ascii (int *pass)
{
//for assigning random values to the array []
random_values(pass,length);
//the printed output from the main fuction is different if I comment this part - random_values() don't work
for (int i = 0; i < length; i++)
{
printf("%d ",pass[i]);
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。