我有一个作业,要求我将字符串指针数组传递给函数,分配字符串,然后读回这些字符串。这是我正在做的事情:
void getStr(char *str[])
{
char temp[256];
strcpy (temp,"Apple");
*str = temp;
printf("\ngetStr Str= %s",*str);
str++;
strcpy (temp,"Mango");
*str = temp;
printf("\ngetStr Str= %s",*str);
str++;
}
int main()
{
char *str[2] ;
int i=0;
getStr (str);
for(i =0 ;i<2;i++)
printf("\nstr addr =%x, str= %s\n",&str[i],str[i]);
return 1 ;
}
Here is my output:
getStr Str= Apple
getStr Str= Mango
str addr =28d623b0, str=
str addr =28d623b8, str=
因此 str 在 getStr() 中正确分配了字符串,但是当我在 main() 中打印它们时,它是空白的。我在这里做错了什么?
最佳答案
您存储到 str
局部变量第一个元素的地址temp
(数组衰减为指针),但该数组的生命周期结束一次 getStr()
返回。因此,您在局部变量的生命周期结束后访问该变量,并导致未定义的行为。
关于c - 将字符串指针数组传递给函数并读取字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26152179/