【发布时间】:2019-07-31 06:28:27
【问题描述】:
假设有这样的函数
int foo (char** str, int x)
{
char* p = *str + x;
foo2(&p); // declared as int foo2 (char** );
}
(当然过于简单了,真正的函数是递归的,而且要复杂得多)
我试过这样做:
int foo (char** str, int x)
{
foo2(&(*str + x));
}
但是编译失败并出现错误:
错误:需要左值作为一元“&”操作数
为什么编译器会出现这个错误,我如何将指针传递给指向字符串 x-byte(s) 转发的指针,而不声明变量并使用它自己的地址?
编辑
似乎有一些误解,所以我将发布一个完整的模拟我想要实现的目标。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* string = "This is a sample string.";
char* ptr;
int randomizer;
int receive_string (char* buffer, int size) // recv
{
int i = 0;
if(ptr == NULL)
ptr = string;
for(i = 0; *ptr != '\0' && i < size; ptr++)
{
if(randomizer == 2)
{
randomizer++;
break;
}
buffer[i] = *ptr;
i++;
randomizer++;
}
if(*ptr == '\0')
{
buffer[i] = *ptr;
i++;
}
return i;
}
int read_string (char* *buffer, int size, int alloc)
{
int bytes = 0;
printf("Reading string..\n");
if(*buffer == NULL && alloc == 1)
{
printf("Allocating buffer..\n");
*buffer = calloc(size, sizeof(char));
}
bytes = receive_string(*buffer, size);
if(bytes == (-1))
{
return(-1);
}
if(bytes == 0)
{
return 0;
}
if(bytes < size)
{
char* p = *buffer + bytes;
//int temp = read_string(&p, size - bytes, 0); // works
//int temp = read_string(&(char *){&(*buffer)[bytes]}, size - bytes, 0); // works
int temp = read_string(buffer + bytes, size - bytes, 0); // doesn't work
if(temp > 0)
bytes += temp;
else return bytes;
}
return bytes;
}
int main()
{
char* buffer = NULL;
int bytes = read_string(&buffer, strlen(string) + 1, 1);
printf("[%u][%s]\n", bytes, buffer);
if(buffer)
free(buffer);
return 0;
}
randomizer 是“模拟”无法接收所有字节的recv() 的最愚蠢的快捷方式。此实现模拟recv(),但不是从套接字队列中读取,而是从全局字符串中读取。
【问题讨论】:
-
@machine_1 编辑了问题以澄清
foo2()具有相同的参数集。这就是为什么我说原始函数是递归的。但是,如果我要制作这样的示例,我将不得不抛出更多的代码来提供一个可以工作而不是死锁的代码,这不是最小的。 -
星星太多。不要成为三星级程序员。如果一个函数分配了,让它返回一个指针。
-
那么为什么不让它返回缓冲区并通过引用传递大小呢?连续的星星越少,越容易理解。有时你当然必须这样做。
-
这毫无意义。你为什么要这样做?
-
@Edenia 但是你发布了代码,它有
free(*buffer);。
标签: c algorithm pointers pointer-arithmetic