2014-03-30 62 views
0

我有一些接收指向char []的指针的函数。C重定向指针

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. 
} 

但我最难重定向我的指针。我认为这个例子会读作“改变指向这个地址的指针”。但是我收到一个编译器警告,“赋值使得指针没有一个强制转换[缺省情况下启用]”。我应该如何重定向我的指针?

+0

它应该是'* number = tmp'。数组的行为类似于指针 – avmohan

+0

v3ga,* number = tmp;返回相同的警告。 – user1695505

+0

实际上它是'number = tmp' – avmohan

回答

1

数组名是一个指向它的第一个元素。你应该使用:

number = temp; 

这将立即解决问题,忽略代码中的任何其他事情。你的输出是错误的,因为你不追加number字符串的空字符末尾。试试:

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'; 
+0

由于tmp是在栈上创建的,所以这仍然不起作用,因此只要函数返回就会超出范围。 – avmohan

+1

printMyPointer(number);在tmp仍在范围内时调用。 printMyPointer(数);没有从main()中调用。检查运行IT的最佳方法。 – deeiip

+0

你说得对。但是,没有用'number = tmp'的用法。你可以做'printMyPointer(tmp)'。 为什么'number = tmp'? – avmohan

-1

它应该是number = tmp。数组的行为与指针类似。 对不起,这是行不通的,因为内存是堆栈分配的。因此,直接在数量,而不是工作的工作在TMP

void foo(char *number, int size) 
{ 
    for(i=0;i<size;i++) //We look to see if the array number points to contains a 1 
    number[i] = (number[i]=='1'?'1':'0');//if not then add a 0. 

    printMyPointer(number); //some function to print the contents of the array pointed to. 
} 

这将在c工作

+0

这仍然返回“赋值使指针没有转换[默认情况下启用]的整数”。 – user1695505

+0

对不起。我已经纠正了错误 – avmohan

+0

number = tmp;将编译,但我收到“▒▒▒▒▒▒▒▒”▒“作为我的输出,当我打印它时,这看起来像一个糟糕的内存引用给我。 – user1695505