簡體   English   中英

struct/constructor/pointer - C 編程語言

[英]struct/constructor/pointer - C programming language

我有一個問題,涉及創建封裝輸入緩沖區的數據結構。 我的問題目前與 malloc 有關,但我覺得它實際上可能是某個指針定義了我出錯了

我必須創建一個構造函數,該構造函數采用 10x10 8 位二維數組並創建它的副本進行處理。

它必須使用以下函數聲明和結構定義。

file - SP.h
typedef struct SP_struct    {
    uint8_t *   base_of_buffer;
    uint16_t    width;
    uint16_t    height;
    uint16_t    x0;
    uint16_t    y0;
    uint8_t     pixel_size;
} SP_struct;

SP_struct*             SP_create           (const unsigned char* s, int width, int height); // constructor

#include "pixel_sum.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main()
{
    uint16_t i = 0;
    unsigned char dummy_array[4][4] = {0,1,0,1,
                                        1,2,1,0,
                                        0,1,4,1,
                                        1,0,1,0};

    printf( "\nMain loop\n" );
    printf( "*dummy_array = %d\n",*dummy_array);

    struct SP_struct *SP_struct_ptr = SP_create(* dummy_array, 4, 4);
    struct SP_struct *SP_struct_ptr2 = SP_create(* dummy_array, 4, 4); // if this line is un commented it works fine
    printf("FINISHED MAIN LOOP");

}

SP_struct*     SP_create(const unsigned char* s, int width, int height){
    uint16_t i = 0;
    printf( "--------------SP_create\n" );
    printf( "*s = %d\n",*s); // This gets value
    printf( "s = %d\n",s); // This gets value

    // printf( "%d\n",width);
    // printf( "%d\n",height);

    SP_struct *p = malloc(width*height*sizeof(p->pixel_size));;
    printf( "p = %d\n",p); // This gets value
    printf( "&p = %d\n",&p); // This gets value
     p->x0 = 12;
     p->y0 = 12;
    //p 
    printf( "p->base_of_buffer = %d\n",p->base_of_buffer);
    printf( "&p->x0 = %d\n",&p->x0);
    printf( "p->x0 = %d\n",p->x0);
    printf( "p->y0 = %d\n",p->y0);
    for(i = 0; i< width*height; i++) {
        p->base_of_buffer[0+i] = s[i];
        //printf( "%d . ",i);
        printf( "%d\n",p->base_of_buffer[0+i]);
    }

    return p    ;
}

當我用 SP_struct_ptr2 注釋掉的行運行它時,它運行良好並給了我一個指針和正確的地址.. 在此處輸入圖片說明

但是當我在 SP_struct_ptr2 行中評論時,我得到.. 在此處輸入圖片說明

有任何想法嗎? 我在 Windows 64 位上使用 gcc 6.3.0,這些是編譯中的唯一文件。

您需要分別分配SP_structbase_of_buffer 您的代碼可能應該是這樣的:

SP_struct*     SP_create(const unsigned char* s, int width, int height){
    ...
    SP_struct *p = malloc(sizeof(*p));
    if (p) {
        p->pixel_size = PIXEL_SIZE;
        p->base_of_buffer = malloc(width*height*sizeof(p->pixel_size)*sizeof(*p->base_of_buffer));
        ...
    }
    return p;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM