struct的打印值显示不正确的值

时间:2019-03-09 20:38:22

标签: c pointers struct

这是我的代码:

public function handle(UploadedFile $image)
{
    $disk = FilesystemHelper::getDisk('producerData');
    $originalName = basename($image->getClientOriginalName(), '.'.$image->getClientOriginalExtension());
    $extension = $image->getClientOriginalExtension();

    $dbImage = new Image();

    // Store image in original size
    $path = $image->storeAs(
        'producers/' . $this->getVehicle()->producer->id . '/vehicles/' . $this->getVehicle()->id, // Folder or Directory
        $image->getClientOriginalName(), // File Name
        $disk // Disk
    );
    Storage::disk($disk)->setVisibility($path, 'public');

    $dbImage->original = $path;
    $dbImage->disk = $disk;

    $file = ImageManipulator::make($image);

    foreach(config('images.vehicles.formats') as $format => $values){
        $file->backup();
        $fileName = $originalName . '-' . str_random(6) . '-' . $values['width'] . 'x' . $values['height'] . '.' . $extension;
        if($format === 'thumbnail'){
            $file->fit($values['width'],$values['height'])
                ->save();
        } else {
            $file->fit($values['width'], $values['height'], function ($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize();
            })->save();
        }
        $path = $image->storeAs(
            'producers/' . $this->getVehicle()->producer->id . '/vehicles/' . $this->getVehicle()->id, // Folder or Directory
            $fileName, // File Name
            $disk // Disk
        );

        Storage::disk($disk)->setVisibility($path, 'public');
        $dbImage->{$format} = $path;
        $file->reset();
    }

    $dbImage->save();
    $this->getVehicle()->images()->attach($dbImage->id);
    $this->getVehicle()->save();
}

运行此命令时,这些是其中一些中间值:

struct mys {
    double d[128];
};

int main() {
    int iters = 2;
    struct mys a[iters];

    for(int i = 0; i < iters; i++) {
        a[i].d[0] = (double)i;
    }

    for(int j = 0; j < 128; j++) {
        printf("%f\n", a[0].d[j]);
    }
}

并打印0.000000 11711905921668651127245114035463936382624607367372861618952521785051367817533820282282998171146926539504166684405188272240881137800884065610400809119241048416797589504.000000 0.000000 0.000000 0.000000 0.000000 也在中间显示a[1]。为什么会这样?

1 个答案:

答案 0 :(得分:1)

您的初始化代码错误。您在堆栈struct mys上声明了一个大小为2的数组,并使用较大的大小对其进行索引(在编辑后)访问未初始化的成员。这是未定义的行为。任何事情都会发生。

使用嵌套的for循环进行初始化,如下所示:

    for(int i = 0; i < iters; i++) {
        /* since we have a struct with an array, initialize each element using a nested for loop. */
        for(int j = 0; j < 128; j++) {
            a[i].d[j] = (double)i;
        }
    }

您可能打算将此嵌套为for循环使用(每个元素的值都不同):

    for(int i = 0; i < iters; i++) {
        /* since we have a struct with an array, initialize each element using a nested for loop. */
        for(int j = 0; j < 128; j++) {
            a[i].d[j] = (double)j;
        }
    }