用0初始化数组,以避免在2D数组中存储垃圾数据,C

用0初始化数组,以避免在2D数组中存储垃圾数据,C,c,arrays,malloc,calloc,C,Arrays,Malloc,Calloc,我想通过计算14幅图像的每个像素的平均值来创建一个光栅数据集。图像为10980*10980,共14幅 主要方案是: //Main program int main() { char path[100]; char suffix[100]; printf("Enter path to list files: "); scanf("%s", path); printf("Enter the wildcard: "); scanf("%s", suff

我想通过计算14幅图像的每个像素的平均值来创建一个光栅数据集。图像为10980*10980,共14幅

主要方案是:

//Main program
int main()
{
    char path[100];
    char suffix[100];

    printf("Enter path to list files: ");
    scanf("%s", path);
    printf("Enter the wildcard: ");
    scanf("%s", suffix);

    struct Node *B02;
    B02 = NULL;
    struct Node *SCL;
    SCL = NULL;
    B02 = recurList(path, suffix);
    printf("Printing B02_head!\n");
    show(B02);
    char *suffix_scl = "SCL_10m.tif";
    SCL = recurListSCL(path, suffix_scl);
    printf("Printing files in SCL head:\n");
    show(SCL);
    int B02_length = 0;
    int SCL_length = 0;
    B02_length = getCount(B02);
    SCL_length = getCount(SCL);
    printf("BO2 of length: %d\n", B02_length);
    printf("SCL of length: %d\n", SCL_length);

    struct Node* p;
    p = B02 ->next;

    struct Node *s;
    s = SCL ->next;
    int counter = 1;
    int n_imgs;
    n_imgs = B02_length;
    float *l[n_imgs];
    float *scl_l[n_imgs];
    char *out = "B02_avg.tif";
    int nX;
    int nY;
    GDALAllRegister();
    GDALDatasetH hD[n_imgs];
    GDALDatasetH slcD[n_imgs];
    GDALDriverH hDr[n_imgs];
    GDALDriverH sclDr[n_imgs];
    GDALRasterBandH hB[n_imgs];
    GDALRasterBandH sclB[n_imgs];
    for(int i=0; i<n_imgs;i++){
        printf("%s\n", B02->data);
        hD[i] = GDALOpen(B02->data, GA_ReadOnly);
        slcD[i] = GDALOpen(SCL->data, GA_ReadOnly);
        hDr[i] = GDALGetDatasetDriver(hD[i]);
        sclDr[i] = GDALGetDatasetDriver(slcD[i]);
        hB[i] = GDALGetRasterBand(hD[i],1);
        sclB[i] = GDALGetRasterBand(slcD[i],1);
        int nX = GDALGetRasterBandXSize(hB[0]);
        l[i] = (float *) malloc(sizeof(float)*nX);
        scl_l[i] = (float *) malloc(sizeof(float)*nX);
        B02=B02->next;
        SCL=SCL->next;
    }
    nX =GDALGetRasterBandXSize(hB[1]);
    nY = GDALGetRasterBandYSize(hB[0]);
    //int N = nX*nY;
    // Creating output file
    //hD[n_imgs] = GDALCreateCopy(hDr[0], out, hD[0],FALSE,NULL,NULL,NULL);
    //hB[n_imgs] = GDALGetRasterBand(hD[n_imgs],1);
    //l[n_imgs] = (float *) malloc(sizeof(float)*nX);
    //scl_l[n_imgs] = (float *) malloc(sizeof(float)*nX);
    //Accessing the data rowxrow

    printf("Checking the value of keeper.\n");
    printf("%s\n", B02->data);
    printf("pointer\n");
    printf("%s\n", p->data);

    int nrows = n_imgs;
    int ncols = nX;

    int (*arr)[ncols] = malloc(sizeof(int[nrows][ncols]));

    int (*arr_scl)[ncols] = malloc(sizeof(int[nrows][ncols]));

    if(arr == NULL || arr_scl == NULL) {
        printf("malloc failed to allocate memory\n");
    }

    for(int row=0;row<1;row++){
        float *out_line;
        out_line= (float *) malloc(sizeof(float)*nX);
        float *mask_count;
        mask_count = (float*) malloc(sizeof(float)*nX);
        float *avg_line;
        avg_line = (float *) malloc(sizeof(float)*nX);
        int n_null_pix;
        n_null_pix = 0;
        for (int i = 0;i<n_imgs;i++){
            GDALDatasetH scl_raster;
            GDALDatasetH raster;
            GDALAllRegister();
            raster = GDALOpen( p->data, GA_ReadOnly);
            scl_raster = GDALOpen( s->data, GA_ReadOnly);
            GDALRasterBandH raster_band;
            GDALRasterBandH scl_band;
            raster_band = GDALGetRasterBand(raster, 1);
            scl_band = GDALGetRasterBand(scl_raster,1);
            float *line;
            float *line_scl;

            int value;
            int mask;

            line = (float *) CPLMalloc(sizeof(float)*nX);
            line_scl = (float*) CPLMalloc(sizeof(float)*nX);

            GDALRasterIO(raster_band, GF_Read,0, row, nXSize,1, line, nXSize, 1, GDT_Float32, 0, 0);
            GDALRasterIO(scl_band, GF_Read, 0, row, nXSize, 1, line_scl, nXSize, 1, GDT_Float32, 0, 0);

            for(int col=0;col<nXSize; col++){
                value = line[col];
                mask = line_scl[col];

                if(mask == 0 || mask ==1 || mask == 3 || mask == 8 || mask == 9
                || mask == 10 || mask == 11)
                    {   
                    value = 0;
                    printf("val:%d::imgID:%d::COOR(<%d,%d>)\n", value, i, row,col);
                    out_line[col] += value;
                    mask_count[col] += 0;
                    printf("n_imgs:%d, col:%d\n", i, col);
                    arr[n_imgs][col] = value;
                    arr_scl[n_imgs][col] += 0;
                    }
                else
                    {
                    printf("val:%d::imgID:%d::COOR(<%d,%d>)\n", value, i, row,col);
                    out_line[col] += value;
                    mask_count[col] += 1;
                    printf("n_imgs:%d, col:%d\n", i, col);
                    arr[n_imgs][col] = value;
                    arr_scl[n_imgs][col] += 1;
                    }
            }
            CPLFree(line);
            CPLFree(line_scl);
            p = p->next;
            s = s->next;
            }

        for(int i = 0; i <n_imgs; i++){
            for (int j = 0; j <nX; j++){
                int value = arr[i][j];
                int scl_value = arr_scl[i][j];
                printf("row:%d,col:%d,val:%d,scl_value:%d\n",i,j, value, scl_value);
            }
        } 

            /*
        int counter = 0;
        for(int i = 0; i <nY; i++){
            int num;
            num = out_line[i];
            int denom;
            denom = mask_count[i];
            int val;
            val = out_line[i]/mask_count[i];
            int mask_value = mask_count[i];
            printf("%d/%d\n", num,denom);
            printf("val:%d\n", val);
            avg_line[i] = val;
            counter ++; 
        }*/
    //GDALRasterIO(hB[n_imgs], GF_Write,0,row,nX,1,avg_line,nX,1,GDT_Float32,0,0);
    //CPLFree(out_line); 
    //CPLFree(avg_line);  
    //CPLFree(mask_count);
    }    
 return 0;
}
该值用于二维阵列上的迭代


        for(int i = 0; i <n_imgs; i++){
            for (int j = 0; j <nX; j++){
                int value = arr[i][j];
                int scl_value = arr_scl[i][j];
                printf("row:%d,col:%d,val:%d,scl_value:%d\n",i,j, value, scl_value);
            }
        } 
下面是我能够通过扩展名获取光栅文件列表的其余代码:

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "gdal/gdal.h"
#include "gdal/cpl_conv.h"
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <sys/stat.h>
#include<stdio.h>
#include "gdal/gdal.h"
#include "gdal/cpl_conv.h"

int const nYSize = 10980, nXSize = 10980;

//Node Structure for Linked-List
struct Node 
{
    char *data;
    struct Node *next;
};

//Declaring global variables
struct Node *B02_list = NULL;
struct Node *SCL_list = NULL;


// Function to replace a string with another 
// string 
char* str_replace(char* string, const char* substr, const char* replacement) {
    char* tok = NULL;
    char* newstr = NULL;
    char* oldstr = NULL;
    int   oldstr_len = 0;
    int   substr_len = 0;
    int   replacement_len = 0;

    newstr = strdup(string);
    substr_len = strlen(substr);
    replacement_len = strlen(replacement);

    if (substr == NULL || replacement == NULL) {
        return newstr;
    }

    while ((tok = strstr(newstr, substr))) {
        oldstr = newstr;
        oldstr_len = strlen(oldstr);
        newstr = (char*)malloc(sizeof(char) * (oldstr_len - substr_len + replacement_len + 1));

        if (newstr == NULL) {
            free(oldstr);
            return NULL;
        }

        memcpy(newstr, oldstr, tok - oldstr);
        memcpy(newstr + (tok - oldstr), replacement, replacement_len);
        memcpy(newstr + (tok - oldstr) + replacement_len, tok + substr_len, oldstr_len - substr_len - (tok - oldstr));
        memset(newstr + oldstr_len - substr_len + replacement_len, 0, 1);

        free(oldstr);
    }

    free(string);

    return newstr;
}


//Function to insert a node into a Linked-List
struct Node *insert(struct Node *Head, char *value)
{
    struct Node *new_string;
    new_string = (struct Node *)malloc(sizeof(struct Node));
    new_string->data = malloc(strlen(value)+1);
    strcpy(new_string->data,value);
    struct Node *temp;
    temp = (struct Node*)malloc(sizeof(struct Node));

    if (Head == NULL)
    {
        temp -> data = new_string->data;
        Head = temp;
        Head -> next = Head;
    }
    else
    {
        temp ->data = new_string->data;
        temp ->next = Head ->next;
        Head -> next = temp;
    }

    return Head;

}


//Function to check if a string finishes with a suffix
int string_ends_with(const char * str, const char * suffix)
{
    int str_len = strlen(str);
    int suffix_len = strlen(suffix);

    return 
        (str_len >= suffix_len) &&
        (0 == strcmp(str + (str_len-suffix_len), suffix));
}


//Function to show the elements of the Linked-List
void show(struct Node *Head)
{
    struct Node *ptr;

    if (Head == NULL)
    {
        printf("List is empty.!");
        return;
    }

    ptr = Head ->next;
    do
    {
        printf("%s\n", ptr->data);
        ptr = ptr->next;
    } while (ptr != Head->next);

}


//Function to find the files in a directory based on a wildcard
struct Node * recurList(char *basePath, char *suffix)
{
    char path[1000];
    struct dirent *dp;

    DIR *dir = opendir(basePath);
    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            strcpy(path, basePath);
            strcat(path, "/");
           strcat(path, dp->d_name);

        struct stat s;
            if (stat(path, &s) == 0)
            {
                if( s.st_mode & S_IFDIR )
                {
                recurList(path, suffix);
                }
                else if(s.st_mode &S_IFREG)
                {
                if (string_ends_with(path, suffix))
                    {
                    B02_list = insert(B02_list, path);
                    }
                }
            } 
        }
    }
    return B02_list;
    closedir(dir);
}


//Function to find the SCL files in a directory 
struct Node * recurListSCL(char *basePath, char *suffix)
{
    char path[1000];
    struct dirent *dp;

    DIR *dir = opendir(basePath);
    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            strcpy(path, basePath);
            strcat(path, "/");
           strcat(path, dp->d_name);

        struct stat s;
            if (stat(path, &s) == 0)
            {
                if( s.st_mode & S_IFDIR )
                {
                recurListSCL(path, suffix);
                }
                else if(s.st_mode &S_IFREG)
                {
                if (string_ends_with(path, suffix))
                    SCL_list = insert(SCL_list, path);
                }
            } 
        }
    }
    return SCL_list;
    closedir(dir);
}


//Function that counts the number of nodes in a linked-list
int getCount(struct Node* head)
{
    int count = 0;
    struct Node* p;
    p = head ->next;
    do
    {
        printf("%s\n", p->data);
        p = p->next;
        count++;
    } while (p != head->next);

    return count;
}
#包括
#包括
#包括
#包括
#包括“gdal/gdal.h”
#包括“gdal/cpl_conv.h”
#包括
#包括
#包括
#包括
#包括
#包括“gdal/gdal.h”
#包括“gdal/cpl_conv.h”
int const nYSize=10980,nXSize=10980;
//链表的节点结构
结构节点
{
字符*数据;
结构节点*下一步;
};
//声明全局变量
结构节点*B02_list=NULL;
结构节点*SCL_列表=NULL;
//函数将字符串替换为另一个字符串
//串
char*str_替换(char*string,const char*substr,const char*replacement){
char*tok=NULL;
char*newstr=NULL;
char*oldstr=NULL;
int oldstr_len=0;
int substr_len=0;
整数替换_len=0;
newstr=strdup(字符串);
substr_len=strlen(substr);
更换=斯特伦(更换);
if(substr==NULL | | replacement==NULL){
返回新闻TR;
}
而((tok=strstrstr(newstr,substr))){
oldstr=newstr;
oldstr_len=strlen(oldstr);
newstr=(char*)malloc(sizeof(char)*(oldstr_len-substr_len+replacement_len+1));
if(newstr==NULL){
免费(oldstr);
返回NULL;
}
memcpy(newstr、oldstr、tok-oldstr);
memcpy(newstr+(tok-oldstr),替换,替换;
memcpy(newstr+(tok-oldstr)+替换项,tok+子项,oldstr-子项-(tok-oldstr));
memset(newstr+oldstr-substr-len+replacement-len,0,1);
免费(oldstr);
}
自由(弦);
返回新闻TR;
}
//函数将节点插入到链接列表中
结构节点*插入(结构节点*头,字符*值)
{
结构节点*新的_字符串;
新字符串=(结构节点*)malloc(sizeof(结构节点));
新建字符串->数据=malloc(strlen(值)+1);
strcpy(新字符串->数据、值);
结构节点*temp;
temp=(结构节点*)malloc(sizeof(结构节点));
if(Head==NULL)
{
临时->数据=新字符串->数据;
压头=温度;
头部->下一步=头部;
}
其他的
{
临时->数据=新字符串->数据;
温度->下一步=头部->下一步;
头部->下一步=温度;
}
回流头;
}
//函数检查字符串是否以后缀结尾
int字符串以(常量字符*字符串,常量字符*后缀)结尾
{
int str_len=strlen(str);
int后缀_len=strlen(后缀);
返回
(str_len>=后缀_len)&&
(0==strcmp(str+(str_len-后缀_len),后缀));
}
//函数以显示链接列表的元素
无效显示(结构节点*头部)
{
结构节点*ptr;
if(Head==NULL)
{
printf(“列表为空!”;
返回;
}
ptr=头部->下一步;
做
{
printf(“%s\n”,ptr->data);
ptr=ptr->next;
}同时(ptr!=头部->下一步);
}
//函数根据通配符查找目录中的文件
结构节点*递归列表(字符*基本路径,字符*后缀)
{
字符路径[1000];
结构方向*dp;
DIR*DIR=opendir(基本路径);
而((dp=readdir(dir))!=NULL)
{
如果(strcmp(dp->d_name,“.”)=0和&strcmp(dp->d_name,“…”)!=0)
{
strcpy(路径、基本路径);
strcat(路径“/”;
strcat(路径,dp->d_名称);
结构统计;
if(stat(path,&s)==0)
{
if(s.st_模式和s_IFDIR)
{
recurList(路径,后缀);
}
否则如果(s.st\U模式和s\U IFREG)
{
if(字符串以(路径,后缀)结尾)
{
B02\u列表=插入(B02\u列表,路径);
}
}
} 
}
}
返回B02_列表;
closedir(dir);
}
//函数查找目录中的SCL文件
结构节点*recurListSCL(字符*基本路径,字符*后缀)
{
字符路径[1000];
结构方向*dp;
DIR*DIR=opendir(基本路径);
而((dp=readdir(dir))!=NULL)
{
如果(strcmp(dp->d_name,“.”)=0和&strcmp(dp->d_name,“…”)!=0)
{
strcpy(路径、基本路径);
strcat(路径“/”;
strcat(路径,dp->d_名称);
结构统计;
if(stat(path,&s)==0)
{
if(s.st_模式和s_IFDIR)
{
recurListSCL(路径,后缀);
}
否则如果(s.st\U模式和s\U IFREG)
{
if(字符串以(路径,后缀)结尾)
SCL_列表=插入(SCL_列表,路径);
}
} 
}
}
返回SCL_U列表;
closedir(dir);
}
//计算链表中节点数的函数
int getCount(结构节点*头)
{
整数计数=0;
结构节点*p;
p=头部->下一步;
做
{
printf(“%s\n”,p->data);
p=p->next;
计数++;
}while(p!=头部->下一步);
返回计数;
}

有谁能帮我澄清这一点,为什么我不能在2D数组中打印出合理的值,以及我应该使用哪种数组分配函数(malloc或calloc)

>旁白:您可以考虑使用<代码> STRCPY 和<代码> STRCAT< /COD>而不是<代码> MycPy字符串。我看到您甚至使用
memset
来编写字符串终止符,但它们是字符串,因为您最初应用了
strlen
。“初始值是从该位置内存中的任何内容中垃圾收集的”。从
malloc
获取的内存未初始化,因此可以包含任何未定义的内容。使用
calloc<
int (*arr)[ncols] = malloc(sizeof(int[nrows][ncols]));
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "gdal/gdal.h"
#include "gdal/cpl_conv.h"
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <sys/stat.h>
#include<stdio.h>
#include "gdal/gdal.h"
#include "gdal/cpl_conv.h"

int const nYSize = 10980, nXSize = 10980;

//Node Structure for Linked-List
struct Node 
{
    char *data;
    struct Node *next;
};

//Declaring global variables
struct Node *B02_list = NULL;
struct Node *SCL_list = NULL;


// Function to replace a string with another 
// string 
char* str_replace(char* string, const char* substr, const char* replacement) {
    char* tok = NULL;
    char* newstr = NULL;
    char* oldstr = NULL;
    int   oldstr_len = 0;
    int   substr_len = 0;
    int   replacement_len = 0;

    newstr = strdup(string);
    substr_len = strlen(substr);
    replacement_len = strlen(replacement);

    if (substr == NULL || replacement == NULL) {
        return newstr;
    }

    while ((tok = strstr(newstr, substr))) {
        oldstr = newstr;
        oldstr_len = strlen(oldstr);
        newstr = (char*)malloc(sizeof(char) * (oldstr_len - substr_len + replacement_len + 1));

        if (newstr == NULL) {
            free(oldstr);
            return NULL;
        }

        memcpy(newstr, oldstr, tok - oldstr);
        memcpy(newstr + (tok - oldstr), replacement, replacement_len);
        memcpy(newstr + (tok - oldstr) + replacement_len, tok + substr_len, oldstr_len - substr_len - (tok - oldstr));
        memset(newstr + oldstr_len - substr_len + replacement_len, 0, 1);

        free(oldstr);
    }

    free(string);

    return newstr;
}


//Function to insert a node into a Linked-List
struct Node *insert(struct Node *Head, char *value)
{
    struct Node *new_string;
    new_string = (struct Node *)malloc(sizeof(struct Node));
    new_string->data = malloc(strlen(value)+1);
    strcpy(new_string->data,value);
    struct Node *temp;
    temp = (struct Node*)malloc(sizeof(struct Node));

    if (Head == NULL)
    {
        temp -> data = new_string->data;
        Head = temp;
        Head -> next = Head;
    }
    else
    {
        temp ->data = new_string->data;
        temp ->next = Head ->next;
        Head -> next = temp;
    }

    return Head;

}


//Function to check if a string finishes with a suffix
int string_ends_with(const char * str, const char * suffix)
{
    int str_len = strlen(str);
    int suffix_len = strlen(suffix);

    return 
        (str_len >= suffix_len) &&
        (0 == strcmp(str + (str_len-suffix_len), suffix));
}


//Function to show the elements of the Linked-List
void show(struct Node *Head)
{
    struct Node *ptr;

    if (Head == NULL)
    {
        printf("List is empty.!");
        return;
    }

    ptr = Head ->next;
    do
    {
        printf("%s\n", ptr->data);
        ptr = ptr->next;
    } while (ptr != Head->next);

}


//Function to find the files in a directory based on a wildcard
struct Node * recurList(char *basePath, char *suffix)
{
    char path[1000];
    struct dirent *dp;

    DIR *dir = opendir(basePath);
    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            strcpy(path, basePath);
            strcat(path, "/");
           strcat(path, dp->d_name);

        struct stat s;
            if (stat(path, &s) == 0)
            {
                if( s.st_mode & S_IFDIR )
                {
                recurList(path, suffix);
                }
                else if(s.st_mode &S_IFREG)
                {
                if (string_ends_with(path, suffix))
                    {
                    B02_list = insert(B02_list, path);
                    }
                }
            } 
        }
    }
    return B02_list;
    closedir(dir);
}


//Function to find the SCL files in a directory 
struct Node * recurListSCL(char *basePath, char *suffix)
{
    char path[1000];
    struct dirent *dp;

    DIR *dir = opendir(basePath);
    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            strcpy(path, basePath);
            strcat(path, "/");
           strcat(path, dp->d_name);

        struct stat s;
            if (stat(path, &s) == 0)
            {
                if( s.st_mode & S_IFDIR )
                {
                recurListSCL(path, suffix);
                }
                else if(s.st_mode &S_IFREG)
                {
                if (string_ends_with(path, suffix))
                    SCL_list = insert(SCL_list, path);
                }
            } 
        }
    }
    return SCL_list;
    closedir(dir);
}


//Function that counts the number of nodes in a linked-list
int getCount(struct Node* head)
{
    int count = 0;
    struct Node* p;
    p = head ->next;
    do
    {
        printf("%s\n", p->data);
        p = p->next;
        count++;
    } while (p != head->next);

    return count;
}