0

我正在编写一个代码来用它的值替换所有 MACROS。如果我的宏 MAX 的值是 1000,并且在代码中,它必须替换为 1000。(我假设如果 MACROS 是一行中的第一个单词,那么我们不会在该行中替换 MACROS,并且那案子我们会以不同的方式处理。

 //Code to replace MACROS BY THEIR VALUES 

 //line contains the actual one line of the code.  
 //line is initialized to contain as maximum number of charectos(say 100).

 //SrcStr is the macro  and destStr is its value. 

 //This block will be looped  for all lines.

   char* p; 
   p = strstr(line,srcStr);
   if(p != NULL)  //if the srcString is found
   {
      if(strlen(p) != strlen(line)) //special case   
      {
         if( isalnum(*(p-1)) == 0 && isalnum( *(p+strlen(srcStr)))==0 ) 
        // if the next char and prev char to our macro is not a alphabets or digits
             {
/*As answered by medo42 (below)*/     
     memmove(p+strlen(destStr), p+strlen(srcStr),strlen(p+strlen(srcStr)+1);
     memcpy(p,destStr,strlen(destStr));         
             }
           }
         else
         {/* handle differently*/}

       } 

由于我是第一次使用memmoveand memcopy,我怀疑上面的代码是否稳定并且可以正常工作。

上面的代码正确吗?上面的代码对于所有输入情况都稳定吗?

4

2 回答 2

2

I see at least three problems:

  1. memmove shouldn't use sizeof(p) which is always going to be fixed (say 4), it should use strlen(line) - (p + strlen(p) - line)
  2. You need to handle the case where replacing the macro increases the length of the line beyond 100
  3. You need to handle cases where the macro label is surrounded by symbols. i.e., _MACRO_ is not the same as MACRO.
于 2011-08-28T14:01:03.663 回答
1

if(strlen(p) != strlen(line)) Why not simply use if(p != line) here? That should be equivalent, easier to understand and faster (strlen scans the entire string).

isalnum(...) == 0 Personal preference maybe, but I'd write that expression as !isalnum(...) since it's easier to understand the meaning this way.

memmove(p+(strlen(destStr)-strlen(srcStr)),p,sizeof(p)); This looks wrong to me. It will move a number of characters depending on your pointer size, which makes no sense, and if srcStr is longer than destStr, the destination of the move might be a position before the start of the line buffer. If you want to move the remainder of the line to adjust for the changed length, try this: memmove(p+strlen(destStr), p+strlen(srcStr), strlen(p+strlen(srcStr)+1); The +1 is important to move the null terminator as well. Of course, you need to ensure that the line buffer actually provides enough space.

于 2011-08-28T14:03:09.497 回答