为什么这个数组可以容纳比初始化的元素更多的元素?

时间:2019-12-31 06:41:15

标签: c computer-science

char oldword[]="abcde";
  char newword[]="a";
  char sentence[]="abcdabcdabcdabcd";
  int  j;

    int k    = 0;
    int len_old = strlen(oldword);
    int len_new = strlen(newword);
    int lenS    = strlen(sentence);

    int  maximum_result = (lenS / len_old + 1) * len_new + 1;   // think !?
    for(int i=0 ; i<lenS ; i++) {
        for(j=0 ; j<len_old ; j++) {
            if(oldword[j] != sentence[j+i]) {
                break;
            }
        }
        if(j == len_old) {              // oldword is a substring of sentence
            for(j=0 ; j<len_new ; j++) {
                result[k++] = newword[j];
            }
            i += len_old-1;
        }
        else {                          // oldword not a substring of sentence
            result[k++] = sentence[i];
        }
    }
    result[k] = '\0';
    printf("%s",result);

在此代码中,数组结果初始化为5,但最后它包含16个字符,但大小仍为5(strlen为16)。这是怎么发生的? 当我尝试向数组中插入超出其自身大小的更多char时,我得到了Abort陷阱:6.为什么?

0 个答案:

没有答案