在下面的代码中,如果我同时删除 strncpy 它的编译和运行没有段错误。但是使用 strcpy 会引发 seg 错误。在这两种情况下,我都试图修改只读地址吗?那么为什么会出现意外行为..
#include<stdio.h>
#include<string.h>
int main()
{
unsigned char* newPrompt="# ";
static unsigned char* au1CLIPromptStrings [] =
{
"",
"Login: ",
"Password: ",
"0123456789012345678901234",
"0123456789012345678901234",
};
/* here am trying to moodify the read only address */
au1CLIPromptStrings[3] = "# \0";
au1CLIPromptStrings[4] = "# \0";
/* removed two strncpy second time */
printf("a1 = %s and a2 = %s\n",au1CLIPromptStrings[3],au1CLIPromptStrings[4]);
/* here using strcpy am trying to modify */
strncpy(au1CLIPromptStrings[3],newPrompt,strlen(au1CLIPromptStrings[3])) ;
strncpy(au1CLIPromptStrings[4],newPrompt,strlen(au1CLIPromptStrings[4])) ;
}
提前致谢..
我现在面临一个问题。我需要将 au1CLIPromptStrings 的值传递给另一个在许多地方使用的双指针。因此,如果我将 au1CLIPromptStrings 的地址分配给结构 elemet 中的 unsigned char 类型的双指针。现在我无法检索即使地址正确,它的元素也会变为 NULL。我不能在任何地方使用相同的 au1CLIPromptStrings 变量,这是我告诉的 waht 的原型,
unsigned char **newPrompt1 =NULL;
newPrompt1 = au1CLIPromptStrings;
printf("a1 = %s and a2 = %s\n", newPrompt1[3],newPrompt1[4]);
#include<stdio.h>
#include<string.h>
int main()
{
unsigned char *newPrompt="# ";
unsigned char **newPrompt1 =NULL;
unsigned char au1CLIPromptStrings [7][30] =
{
"",
"Login: ",
"Password: ",
" 0123456789012345678901234",
" 0123456789012345678901234",
};
newPrompt1 = au1CLIPromptStrings; // here am assigning the address
printf("b1 = %u and b2 = %u\n",newPrompt1,au1CLIPromptStrings);
printf("a1 = %s and a2 = %s\n",newPrompt1[3],newPrompt1[4]);
}