【发布时间】:2020-09-20 12:31:03
【问题描述】:
我正在尝试打印数组中的值。在 ascii() 中,我打印了这些值以检查这些值是否可以毫无问题地传输到主函数。我还设置了 random_values,这样数组中的所有整数都在 33 到 126 之间。
一切看起来都很好,但问题是当我注释我编写的用于检查 ascii() 内部的部分代码时,主函数中的值会变得混乱。它给了我像 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函数返回一个指向本地(临时)变量的指针。它有时只是“偶然”起作用。 -
在对象生命周期结束后使用指向对象的指针值的未定义行为。
-
你的 random_values 函数做你想做的事,不需要 ascii 函数。从技术上讲,EOF 和 Adrian 是对的,返回局部变量的地址是有风险的。
-
@tango 没有风险。你做不到。
-
@P__J__ 我得到了警告,编译是用 g++ 完成的。