C 使用 strtol 解析字符串函数参数



我对 C 有点陌生,想了解一些关于使用指针和取消引用访问函数参数的事情。

这是我的代码,程序的全部意义在于使用strtol来解析只有两位数字的给定参数,用空格分隔。

int sum(const char *input){
  char *input = input_line;   // dereference the address passed into the function to access the string
  int i; // store sum in here
  char *rest; // used as second argument in strtol so that first int can be added to i
  i = strtol(input, &rest, 10); // set first int in string to i
  i += strtol(rest, &rest, 10); // add first and second int
  return i;
}

我很困惑如何访问给定的字符串参数,因为字符串在变量名称旁边有一个*,我不太确定如何解决这个问题。

无论如何,谢谢。

无需取消引用输入参数。如果你只是简单地放下这条线

char *input = input_line; 

(无论如何,这不是取消引用它的正确方法),代码将起作用。你sum传递一个指向char的指针,这正是strol的第一个参数应该是什么。

一个简单的测试:

#include <stdio.h>
#include <stdlib.h>
int sum(const char *input){
  int i; // store sum in here
  char *rest; // used as second argument in strtol so that first int can be added to i
  i = strtol(input, &rest, 10); // set first int in string to i
  i += strtol(rest, &rest, 10); // add first and second int
  return i;
}
int main(void){
    char* nums = "23 42";
    printf("%dn",sum(nums)); 
    return 0;
}

它按预期打印65

就取消引用

的机制而言:如果出于某种原因您真的想取消引用传递给sum的指针,您会执行以下操作(在sum内):

char ch; // dereferencing a char* yields a char
ch = *input; // * is the dereference operator 

现在ch将保存输入字符串中的第一个字符。根本没有理由将单个char传递给strol因此在这种情况下,这种取消引用是没有意义的 - 尽管有时在函数的主体中取消引用传递给该函数的指针当然有正当的理由。

最新更新