假设有一个这样的函数
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));
}
但是编译器失败并出现错误:
error: lvalue required as unary '&' operand
为什么编译器会抛出此错误?如何将指针传递到指向字符串 x 字节的指针,而不声明变量并使用其自己的地址?
<小时/>编辑
似乎存在一些误解,所以我将发布我想要实现的完整模拟。
#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;
}
随机化器
是“模拟”无法接收所有字节的recv()
的最愚蠢的快速方法。此实现模拟 recv()
但不是从套接字队列读取,而是从全局字符串读取。
最佳答案
(*str + x)
不是左值,因为它是一个没有地址的临时值,因此您无法使用 &
获取其地址。即使编译器将值存储在 RAM 中的临时变量中,以便可以获取其地址,如果 foo2() 修改了临时变量的内容,之后您将如何引用它的值。
因此您需要自己将值存储在临时变量中。
关于c - 将取消引用的指针的地址传递给字符串偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55076490/