If it's a minor mistake that's likely due to inattention, edit. If it's a fundamental mistake that completely invalidates the answer or a large part of it, downvote, comment to explain what is wrong and provide a better answer. If there's something suboptimal but not fundamentally broken, it's generally better to comment. If you can tell that there's something wrong in a side point but you aren't sure what to correct it to, comment.
For example, suppose a question asks how to test whether a file is a directory on Linux and an answer suggests the
stat function and provides this sample code:
if (st.st_mode & S_IFMT == S_IFDIR) …
then edit the answer to add the missing pair of parentheses around
st.st_mode & S_IFMT. The main point of the answer is to point the asker to
stat and the
st_mode field, and the mistake in the sample code is likely due to inattention. On the other hand, if you wanted to recommend using the
S_ISDIR macro, this belongs in a comment (because using the
S_IFMT mask is not actually wrong), and you might want to post that as a separate answer (or just leave it as a comment). If the question was about operator precedence in C, the code above would warrant a downvote.
There is nothing wrong with editing the code of an answer, as long as what you are changing is a secondary point that does not change the intended meaning of the answer, and you are sure that your correction is valid. Be sure to explain your edit in the edit summary (“added parentheses that are necessary due to operator precedence”).
(On the other hand, never edit code in a question, except to fix badly lacking indentation in a language that isn't sensitive to indentation.)
If the code as posted is potentially dangerous, for example because of the risk of SQL injection, the threshold for editing is lower. If the structure of the code is basically correct but some additional quoting needs to be done, edit the answer to add the necessary quoting. If the code works on good input but cannot be easily fixed to cope with arbitrary input, and nothing indicates that the input is assumed to be pre-sanitized, downvote and explain the problem in a comment. If the question states that the input is already sanitized, but the answer doesn't mention this, it may be worth commenting on the answer to remind readers that the answer assumes sanitized input.