使用Array的分段错误

时间:2017-04-22 23:45:44

标签: c++ c arrays pointers segmentation-fault

如果我写如下,则发生分段错误。但如果我写 my_strings <- c("What can we learn from the Mahabharata ", "What are the most iconic songs associated with the Vietnam War ", "What are some major social faux pas to avoid when visiting Malta ", "Will Ready Boost technology contribute to CFD software usage ", "Who is Jon Snow ", "Do weighing scales measure mass or weight ", "What will happen to the money in foreign banks after demonetizing 500 and 1000 rupee notes ", "Is it mandatory to stay for 11 months in a rented house if the rental agreement was made for 11 months ", "What are some really good positive comments to say on a cricket field to your teammates ", "Is Donald Trump fact free ") word_scores <- data.frame(word = c("the", "to", "What", "I", "a", "are", "in", "of", "and", "do" ), score = c(11L, 9L, 9L, 7L, 6L, 6L, 6L, 6L, 3L, 3L), stringsAsFactors = F) printf(messages[0]),我就没有错误。为什么?我想用“for”打印所有数组成员。

printf(messages[1])

1 个答案:

答案 0 :(得分:0)

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

void 
givetag(char *array[])  
{ 
    int i;
    for(i=0; i<3; i++){
        array[i]= (char*) malloc(100);
        scanf("%s", array[i]);
    }
} 

int main()
{
    char* messages[3];
    givetag(messages); //sub function 

    int i;

    for(i=0;i<3;i++) { 
        printf(messages[i]);
    }

    printf("\n");

    return 0;
}

如右图所示,你必须添加malloc大小(我改变代码)。

1