简体   繁体   English

指针数组,改变指针元素

[英]Array of pointers, changing pointer elements

If I declare an array of pointers like that:如果我声明一个这样的指针数组:

    char* arr[5] = {"Mercury",
    "Mercury",
    "Venus",
    "Earth",
    "EArth"};

Can I then change sings in those pointers?然后我可以更改这些指针中的歌曲吗? I have tried doing something like that我试过做这样的事情

*(*(arr + 1) + 1) = 'i';

but it doesn't work, I get memory dump.但它不起作用,我得到 memory 转储。 Is there a way to do that or I have to declare it differently?有没有办法做到这一点,或者我必须以不同的方式声明它?

Is there a way to do that or I have to declare it differently?有没有办法做到这一点,或者我必须以不同的方式声明它?

char* arr[5] = {"Mercury", "Mars", "Venus", "Earth", "Pluto"};

arr is an array of 5 char pointers to string literals. arr是一个包含 5 个指向字符串文字的char指针的数组。 Any attempt to modify a string literal invokes undefined behavior, so you can´t modify them.任何修改字符串文字的尝试都会调用未定义的行为,因此您无法修改它们。

If you want to modify the content you need fe to define them as two-dimensional array of char s:如果要修改内容,则需要 fe 将它们定义为char的二维数组:

char arr[5][10] = {{"Mercury"}, {"Mars"}, {"Venus"}, {"Earth"}, {"Pluto"}};

and use并使用

strcpy(arr[0], "Uranus");

size_t len = strlen(arr[0]);  
for(size_t i = 9; i > (len + 1); i--)  // To remove all left characters from prev. string.
{
    a[0][i] = '\0';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM