C重定向指针
我有一个函数,它接收指向char[]的指针C重定向指针,c,pointers,redirect,C,Pointers,Redirect,我有一个函数,它接收指向char[]的指针 void foo(char *number, int size) { char tmp[size]; for(i=0;i<size;i++) //We look to see if the array number points to contains a 1 tmp[i] = (number[i]=='1'?'1':'0');//if not then add a 0. *number = &tmp; //PROB
void foo(char *number, int size)
{
char tmp[size];
for(i=0;i<size;i++) //We look to see if the array number points to contains a 1
tmp[i] = (number[i]=='1'?'1':'0');//if not then add a 0.
*number = &tmp; //PROBLEM LINE
printMyPointer(number); //some function to print the contents of the array pointed to.
}
void foo(字符*数字,整数大小)
{
字符tmp[大小];
for(i=0;i数组名在c
中是指向其第一个元素的指针。您应该使用:
number = temp;
这将立即解决问题,忽略代码中的任何其他内容。您的输出是错误的,因为您没有在number
string的末尾追加空字符。请尝试:
for(i=0;i<size-1;i++) //We look to see if the array number points to contains a 1
tmp[i] = (number[i]=='1'?'1':'0');//if not then add a 0.
tmp[size-1] = '\0';
for(i=0;iIt应该是*number=tmp
。数组的行为类似于pointersv3ga,*number=tmp;返回相同的警告。实际上它是number=tmp
这仍然不起作用,因为tmp是在堆栈上创建的,因此一旦函数返回就会超出范围。printMyPointer(number)当tmp仍在作用域下时调用;。不会从main()调用printMyPointer(number);检查的最佳方法是运行它。您是对的。但是,执行number=tmp
。您也可以执行printMyPointer(tmp)
。为什么number=tmp
?我不应该为op编写更好的代码。我可以纠正它们。op就是这样写的。我假设number=tmp
的意图是op打算在函数返回后将数字指向修改后的值。