编辑char *数组 [英] Edit an array of char*

查看:143
本文介绍了编辑char *数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 char * 像这样:

  char * gradient_xpm [] = {abc,def,ghi}; 

我需要更改这些字符串的值。



我尝试了 strcpy = 操作符,但它给我一个分段错误。 p>

例如:

  strcpy(gradient_xpm [1],jkl) ; 
gradient_xpm [1] [2] ='x';

我无法编辑单个字符。如何编辑这些值?

解决方案

在数组中有字符串常量,不能更改。这是你的segfaults的原因。



你需要设置你的数组不使用字符串常量,然后复制字符串常量到你的数组。



类似:

  char * gradient_xpm [3] 

gradient_xpm [1] =(char *)malloc(sizeof(char)*(MAX_STR_LEN + 1));
strncpy(gradient_xpm,jkl,MAX_STR_LEN);

//现在这将工作:
gradient_xpm [1] [2] ='x';类似地,对于 gradient_xpm [0]



gradient_xpm [2]


I have an array of char * like this:

char * gradient_xpm[] = {"abc", "def", "ghi"};

I need to change the value of those strings.

I've tried strcpy and the = operator, but it gives me a Segmentation Fault.

e.g:

strcpy(gradient_xpm[1],"jkl");
gradient_xpm[1][2] = 'x';

I wasn't able to edit even a single char. How can I edit those values?

解决方案

You have string constants in your array, and those can't be changed. This is the cause of your segfaults.

You'll need to setup your array without using string constants, then copy the string constants into your array.

Something like:

char *gradient_xpm[3];

gradient_xpm[1] = (char *) malloc(sizeof(char) * (MAX_STR_LEN + 1));
strncpy(gradient_xpm, "jkl", MAX_STR_LEN);

// now this will work:
gradient_xpm[1][2] = 'x';

Similarly for gradient_xpm[0], gradient_xpm[2].

这篇关于编辑char *数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆