如何在不内存泄漏的情况下删除C中的前导/尾随空格

时间:2019-05-20 09:29:28

标签: c memory-management

假定某些字符串(带有前导/后缀空格)已分配了内存。

void s_trim(char *str)
{
  char *end;
  while(isipace((unsigned char)* str)) str++; // trim leading
  end = str+strlen(str)-1;
  while(end>str && isspace((unsigned char)* end)) end--;
}

int main()
{
 char *test = (char*) malloc(12*sizeof(char));
 strcpy(test, "  abc def  "); // <2*spaces>+abc+<space>+def+<2*spaces>
 s_trim(test); // i'm going to use this to get "abc def" 
 free(test); // is this going to free all allocated memory [malloc(12*sizeof(char))] ?
}

1 个答案:

答案 0 :(得分:1)

您的函数str不会在数组str中进行任何更改,也不会返回任何内容。指针char* s_trim(char *str) { char *end; while(isspace((unsigned char)* str)) str++; // trim leading end = str+strlen(str)-1; while(end>str && isspace((unsigned char)* end)) end--; *(end +1) = '\0'; return (str); } int main() { char *test = (char*) malloc(12*sizeof(char)); char * trimmed; strcpy(test, " abc def "); // <2*spaces>+abc+<space>+def+<2*spaces> trimmed = s_trim(test); // i'm going to use this to get "abc def" printf ("Result = __%s__\n",trimmed); free(test); } 中的任何更改都是该函数的局部内容,不会导致输入字符串的修剪。

要进行修整,您需要具有该函数的返回值,该值将提供修改后的指针。

db.torder.aggregate([
        {$match:{$and:[{TANGGALPI:{$gte:'2019-01-01'}},{TANGGALPI:{$lte:'2019-12-31'}}]}},
        {$lookup:{
                from:"tsales",
                localField:"IDSALES",
                foreignField:"SALESCODE",
                as:"SALESINFO"
        }},
        {$group:{
                _id:"$CUSTNAME",SALES:{$first:"$SALESINFO.NAMASALES"},TOTAL : { $sum: {$multiply:["$QTY","$PRICE"]}}}},
        {$sort:{TOTAL:-1}}
])