【问题标题】:C Print value in main() is different if I don't print some values in a different function [duplicate]如果我不在不同的函数中打印某些值,C 在 main() 中的打印值会有所不同[重复]
【发布时间】: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++ 完成的。

标签: arrays c pointers memory


【解决方案1】:

您正在发送一个局部变量的指针。 我会将 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;
}

【讨论】:

  • 是的,我忘了在main中添加,调用ascii(密码);
  • 谢谢!现在一切都很好!
  • @lemnel — 欢迎来到 Stack Overflow。请注意,在这里说“谢谢”的首选方式是投票赞成好的问题和有用的答案(一旦你有足够的声誉这样做),并接受对你提出的任何问题最有帮助的答案(这也给出了你的声誉小幅提升)。请查看About 页面以及How do I ask questions here?What do I do when someone answers my question?
猜你喜欢
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多