Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

c - Are the strings in argv modifiable?

I just wrote a small program that reads command line arguments in C, nothing too difficult. I was also modifying them, for example changing the first character of the parameter to uppercase.

I know that you shouldn't modify string literals as it can cause undefined behavior, so was just wondering if the strings in the *argv[] are literals that you shouldn't change.

int main(int argc, char *argv[])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the C11 standard draft N1570, §5.1.2.2.1/2:

The parameters argc and argv and the strings pointed to by the argv array shall be modi?able by the program, and retain their last-stored values between program startup and program termination.

They are modifiable. That means they are not string literals.

But be careful: the upper citation only refers to pointers to strings, excluding the obligatory null pointer at argv[argc]1.
From the C11 standard draft N1570, §5.1.2.2.1/2 (same as above)1:

argv[argc] shall be a null pointer


Notes:

  • Something regarding this sentence:

    I know that you shouldn't modify string literals as it can cause undefined behavior [...]

    "can"? It does always. Undefined behavior includes expected, as if well-defined, and unexpected behavior.


1 Thanks to @black!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...