gpt4 book ai didi

c - 当我们尝试在函数中复制字符数组时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:39:15 24 4
gpt4 key购买 nike

<分区>

当我尝试将一些值复制到从主函数传递的 char 数组时,我遇到了段错误。

请找到附件中的代码示例,请帮助我哪里出错了。

#include <stdio.h>
#include <string.h>

void getVal(char val[]){
strcpy(val[0],"abcdef"); //segfault.
}


int main(int argc, char **argv)
{
char val[64] = { 0 };
getVal(&val[0]);
printf("%s",val);
}

发布了实际代码,当数组 strcpy 的 char 工作正常但通过函数调用时它给出了段错误。请帮助我。

#include <time.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "ezxml.h"

static ezxml_t root;

void load_xml(char *root_node){

root = ezxml_parse_file(root_node);
printf("%p\n",root);
}

void getParamVal(char *objname, char val[]){

char *char_strip;
const char *tmp_buf[20];
int i=0;

ezxml_t get_child_tmp;
const char *attrvalue;

char_strip = strtok (objname,".");
while (char_strip != NULL)
{
tmp_buf[i] = char_strip;
char_strip = strtok (NULL, ".");
i++;
}



for (get_child_tmp = ezxml_child(root,tmp_buf[1]); get_child_tmp; get_child_tmp = get_child_tmp->next) {
attrvalue = ezxml_attr(get_child_tmp, "instance");
if(!(strcmp(attrvalue,tmp_buf[2]))){
ezxml_t get_child_level1;
for (get_child_level1 = ezxml_child(get_child_tmp,tmp_buf[3]); get_child_level1; get_child_level1 = get_child_level1->next) {
attrvalue = ezxml_attr(get_child_level1, "instance");
if(!(strcmp(attrvalue,tmp_buf[4]))){
ezxml_t get_child_level2;
for (get_child_level2 = ezxml_child(get_child_level1,tmp_buf[5]); get_child_level2; get_child_level2 = get_child_level2->next) {
attrvalue = ezxml_attr(get_child_level2,"instance");
if(!(strcmp(attrvalue,tmp_buf[6]))){
printf("%s\n",ezxml_child(get_child_level2,tmp_buf[7])->txt);
char s[10];
strcpy (s,ezxml_child(get_child_level2,tmp_buf[7])->txt); // fine with local array of char
printf("%s\n",s);
strcpy(val, ezxml_child(get_child_level2,tmp_buf[7])->txt); // problem gives segfault only diff is val is from other function.
}
}
}
}
}
}
}


int main(int argc, char **argv)
{

if (argc < 2){
printf("usage: ./test <xml file> ");
exit(1);
}

struct timeval tv;
unsigned int seconds=0, mseconds=0;

char val[64] = { 0 };
char objname[]="a.b.c.d.e.f.c";

load_xml(argv[1]);

gettimeofday(&tv, NULL);
seconds = tv.tv_sec;
mseconds = tv.tv_usec;
printf("START: [%u][%u]\n", seconds, mseconds);

getParamVal(&objname[0],&val[0]);

gettimeofday(&tv, NULL);
seconds = tv.tv_sec;
mseconds = tv.tv_usec;
printf(" END: [%u][%u]\n", seconds, mseconds);
return 0;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com