简体   繁体   English

无法将C程序与strsep()和getenv()一起使用

[英]Cant get C program and strsep() and getenv() to all work together

I had this working before, but I was using pointers. 我以前曾做过这项工作,但是我正在使用指针。 getenv() keeps crashing so I copied the results using sprintf(). getenv()一直崩溃,所以我使用sprintf()复制了结果。 Now I want to deliminate with : and print only the first occurrence. 现在我想用:代替,只打印第一次出现。 Please help! 请帮忙!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(void) {

    char buf[999];
    const char *token;

    // HTTP_PROXY == 8.8.8.8:8888, end result should print 8.8.8.8

    sprintf(buf, "%s", getenv("HTTP_PROXY"));
    *token = strsep(&buf, ":");
    printf("New result: %s\n", token);

}

Since strsep wants a pointer to pointer, you must pass a pointer to pointer, not a pointer to array. 由于strsep一个指向指针的指针,因此必须传递一个指向指针的指针,而不是一个指向数组的指针。 This is not the same thing; 不是一回事。 make a pointer, and assign it buf . 创建一个指针,并将其分配给buf Pass a pointer to that new pointer to strsep to fix the first problem. 将指向该新指针的指针传递给strsep以解决第一个问题。

The second problem is that since strsep returns a pointer, you need to assign it to token , not to *token : 第二个问题是,由于strsep返回一个指针,因此您需要将其分配给token ,而不是*token

char buf[999];
const char *token;
// HTTP_PROXY == 8.8.8.8:8888, end result should print 8.8.8.8
sprintf(buf, "%s", getenv("HTTP_PROXY"));
char *ptr = buf;           // Since ptr, is a pointer...
token = strsep(&ptr, ":"); // ...you can pass a pointer to pointer
printf("New result: %s\n", token);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  char const *http_proxy = getenv("HTTP_PROXY");
  if (http_proxy == NULL) {
    fprintf(stderr, "HTTP_PROXY not set: default 8.8.8.8:8888");
    http_proxy = "8.8.8.8:8888";
  }

  char *cpy = strdup(http_proxy);
  char *token = strtok(cpy, ":");
  if (token == NULL) {
    fprintf(stderr, "wrong format");
    return 1;
  }
  do {
    printf("Token: %s\n", token);
  } while ((token = strtok(NULL, ":")) != NULL);
  free(cpy);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM