簡體   English   中英

分段故障(核心已轉儲)

[英]Segmentation fault (core dumped)

下面的代碼可以在'temp'中復制'str'的其他所有元素,但是如果我僅增加'* str'一次,則會給我一個分段錯誤(內核已轉儲)。 我試圖將字符串的所有偶數字母和奇數字母都復制到“偶數”數組中(“偶數”是第二個字母,第四個,第六個等),但是我意識到當我增加它保持增加。 我真的不知道該如何解決,所以我嘗試將字母存儲在函數內的另一個數組中,但是遇到了段錯誤。 我不明白為什么增加兩次就可以,但一次不行。

#include <stdio.h>
#include <string.h>
#define N 100

void encrypt(const char*);

int main(void)
{
    char str[N];
    printf("Please enter a message: ");
    gets(str);

    encrypt(&str);
return 0;
}

void encrypt(const char *str)
{
    int i, j, length;
    char temp[N], odd[N], even[N];

    length = strlen(str);

    for (j = 0; *str < *str + length; *str++, *str++, j++)
    {
        temp[j] = *str;
    }
    printf("%s", temp);
}

我想您實際上是想寫這樣的:

for (j = 0; str < str + length; *str++, *str++, j++)

可以這樣寫,這更加清楚:

for (j = 0; str < str + length; str++, str++, j++)

但是無論如何這都是錯誤的,因為str < str + length總是正確的。

這是您需要的:

for (j = 0; j < length; j++)
{
  temp[j] = *str;
  str += 2;
}

暫無
暫無

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

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