簡體   English   中英

C - 我可以從char *創建一個const char *變量嗎?

[英]C - can I create a const char * variable from char *?

我想要這樣做的原因是因為我想逐行讀取文件,並且每行檢查它是否與正則表達式匹配。 我正在使用getline()函數,它將行放入char *類型變量。 我試圖使用regexec()來檢查正則表達式匹配,但是這個函數要求你提供匹配的字符串作為const char *

所以我的問題是,我可以從char *創建一個const char * char *嗎? 或者是否有更好的方法來解決我在這里要解決的問題?

編輯:我被要求提供一個例子,我沒有想到並為首先沒有給出一個而道歉。 在寫這篇文章之前,我確實讀過@chqrlie的答案。 以下代碼給出了分段錯誤。

#define _GNU_SOURCE                                                                                                
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>
#include <regex.h>

int main() {
  FILE * file = fopen("myfile", "r");
  char * line = NULL;
  size_t len = 0;
  ssize_t read;

  regex_t regex;
  const char * regexStr = "a+b*";

  if (regcomp(&regex, regexStr, 0)) {
    fprintf(stderr, "Could not compile regex \"%s\"\n", regexStr);
    exit(1);
  }

  while ((read = getline(&line, &len, file)) != -1) {
    int match = regexec(&regex, line, 0, NULL, 0);

    if (match == 0) {
      printf("%s matches\n", line);
    }
  }

  fclose(file);

  return 0;
}

char *可以轉換為const char *而無需任何特殊語法。 此類型的const意味着指針指向的數據不會通過此指針進行修改。

char array[] = "abcd";  // modifiable array of 5 bytes
char *p = array;        // array can be modified via p
const char *q = p;      // array cannot be modified via q

這里有些例子:

int strcmp(const char *s1, const char *s2);
size_t strlen(const char *s);
char *strcpy(char *dest, const char *src);

正如您所看到的, strcmp不會修改它接收指針的字符串,但您當然可以將常規的char *指針傳遞給它。

類似地, strlen不會修改字符串, strcpy會修改目標字符串,但不會修改源字符串。

編輯:你的問題與constness轉換無關:

  • 你沒有檢查fopen()的返回值,程序在我的系統上產生分段錯誤,因為myfile不存在。

  • 您必須傳遞REG_EXTENDED以使用較新的語法(例如a+b*編譯正則表達式

這是一個更正版本:

#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>

int main() {
    FILE *file = fopen("myfile", "r");
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    regex_t regex;
    const char *regexStr = "a+b*";

    if (file == NULL) {
        printf("cannot open myfile, using stdin\n");
        file = stdin;
    }

    if (regcomp(&regex, regexStr, REG_EXTENDED)) {
        fprintf(stderr, "Could not compile regex \"%s\"\n", regexStr);
        exit(1);
    }

    while ((read = getline(&line, &len, file)) != -1) {
        int match = regexec(&regex, line, 0, NULL, 0);
        if (match == 0) {
            printf("%s matches\n", line);
        }
    }

    fclose(file);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM