字符串分割错误

segmentation fault in string

本文关键字:错误 分割 字符串      更新时间:2023-10-16

我只是想从字符串中提取两个子字符串。但它显示出分割错误。

代码为

const char *str;  
char *s1, *s2;
str = "name:d";  
char *pos = strchr(str, ':');
size_t no    = 1,
       index = pos - str;
if (index > 0) 
{
    strncpy(s1, str, index);  
    cout << "name is:" << s1;  
    index++;  
    strncpy(s2, str + index, no);  
    cout << "direction is:" << s2;       
}

将以下两行复制到未初始化指针引用的内存中:

 strncpy(s1,str,index);  
 strncpy(s2,str+index,no);  

您需要为s1s2分配内存(或者只使用std::string,避免自己的头痛)。

您没有为s1s2分配任何内存。您需要做的是使用new并分配内存,或者使用std::string并节省麻烦。

您没有初始化s1s2来指向任何东西;因此,试图写入他们指向的内存(例如strncpy(s1,str,index))会给出未定义的行为-如果你幸运的话,一个分段错误。

如果你在写C,那么为它们分配内存;如果您正在编写c++,请使用std::string为您管理内存分配。