gpt4 book ai didi

c - 我是在这里创建了两个单独的指针,还是我正确地调用了作为命令的单个内存地址?

转载 作者:行者123 更新时间:2023-12-04 07:14:40 25 4
gpt4 key购买 nike

要指定我的问题,我是在使用函数时直接引用 int main 中的命令,还是复制它们,然后使用函数引用这些副本?我无法理解 C 中的指针和字符串。
此外,如果我以一种非常愚蠢的方式进行此错误检查,并且您知道它可以如何更好,我很乐意受到启发。我来自 Python,并且仍在很大程度上学习 C。我目前的目标是编写一个非常小的编译器来做简单的加法。

#include <stdio.h>

int CompilationErrorChecking(int argc, char *argv[]){
// Check initialy if for at least one argument attatched to Iwa
if (argc < 2 && argc == 1){
printf("Error: No arguments found");
// If the arguments are correct: Iwa_Compiler <FileName>
// Execute, and say the command back to them
} else if (argc <= 2){
printf("%s %s\n", argv[0], argv[1]);
// If there are more than 2 arguments, spit error
} else {
printf("Erorr: Too many arguments");
}
return 0;
}

int main(int argc, char *argv[]) {
CompilationErrorChecking(argc, argv);
return 0;
}

最佳答案

int CompilationErrorChecking(int argc, char *argv[]) {
...
}

int main(int argc, char *argv[]) {
CompilationErrorChecking(argc, argv);
...
}
你路过 argcargv到助手功能正确。你写的东西超过了计数 argc和指针 argv ,它们都是廉价的副本,并且不进行任何昂贵的字符串复制。 (实际上很难意外地进行昂贵的复制。您必须明确调用 strcpy()memcpy() 或其他类似函数。)
if (argc < 2 && argc == 1){
printf("Error: No arguments found");
// If the arguments are correct: Iwa_Compiler <FileName>
// Execute, and say the command back to them
} else if (argc <= 2){
printf("%s %s\n", argv[0], argv[1]);
// If there are more than 2 arguments, spit error
} else {
printf("Erorr: Too many arguments");
}
当我们在这里时,值得指出的是这些 argc检查是不对的。对于第一个你想在没有参数时出错的情况,当 argc < 2 时会发生这种情况。或 argc <= 1 (这些是等价的)。额外的 && argc == 1没有帮助。
对于第二个,您应该检查 argc == 2 . <=具有误导性,因为 else if如果 argc,块实际上会失败小于 2。

关于c - 我是在这里创建了两个单独的指针,还是我正确地调用了作为命令的单个内存地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68840064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com