无法更改 char * c 指向的地址

标签 c char mbedtls

我在这个函数内接收一个缓冲区,我想通过将缓冲区地址增加一来忽略第一个字符。

我增加了缓冲区,但在函数之外,缓冲区包含接收到的数据,但它没有增加。

奇怪了!!谁能帮帮我!!

int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
                  uint32_t timeout )
{
int ret,recv;
struct timeval tv;
fd_set read_fds;
int fd = ((mbedtls_net_context *) ctx)->fd;

if( fd < 0 )
    return( MBEDTLS_ERR_NET_INVALID_CONTEXT );

FD_ZERO( &read_fds );
FD_SET( fd, &read_fds );

tv.tv_sec  = timeout / 1000;
tv.tv_usec = ( timeout % 1000 ) * 1000;

ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );

/* Zero fds ready means we timed out */
if( ret == 0 )
    return( MBEDTLS_ERR_SSL_TIMEOUT );

if( ret < 0 )
{
#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \
!defined(EFI32)
    if( WSAGetLastError() == WSAEINTR )
        return( MBEDTLS_ERR_SSL_WANT_READ );
#else
    if( errno == EINTR )
        return( MBEDTLS_ERR_SSL_WANT_READ );
#endif

    return( MBEDTLS_ERR_NET_RECV_FAILED );
}

/* This call will not block */
recv = mbedtls_net_recv( ctx, buf, len );
buf = buf + 1;
printf("Receiving\n");

return( recv );
}

最佳答案

正如 Eugene Sh 所说,C 中的参数是按值传递的。

示例:

void Test(int value)
{
  value++;
}

...

int foo = 3;
Test(foo);
// here, foo is still 3

如果你想在C中通过引用传递foo,你需要传递它的指针

void Test(int* value)
{
  *value++;
  value++;
}

...

int foo = 3;
int *fooPtr = &foo;
Test(fooPtr);
// Now, foo is 4, but fooPtr still is &foo.

请注意,我还在 Test() 函数内递增了指针,但由于指针本身是按值传递的,因此它不会在 Test() 函数外部递增.

为了实现你想要的,你需要通过引用传递指针(作为指针):

void Test(int** value)
{
  **value++;
  *value++;
}

...

int foo = 3;
int *fooPtr = &foo;
Test(&fooPtr);
// Now, foo is 4, and fooPtr was incremented.
// This is just an example ; don't use fooPtr beyond this point, its value is wrong.

您需要传递 buf 指针作为引用才能更改指针值:

int mbedtls_net_recv_timeout( void *ctx, unsigned char **buf, size_t len,
                  uint32_t timeout )
{

  [... snip ...]

  /* This call will not block */
  recv = mbedtls_net_recv( ctx, *buf, len );
  *buf = *buf + 1;
  printf("Receiving\n");

  return( recv );
}

关于无法更改 char * c 指向的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49778962/

相关文章:

c++ - 将 unsigned char 转换为 int 和 short

使用 openssl 将代码转换为使用 mbedtls

c - 使用 mbedlts 在内存受限的系统上使用 SHA 散列文件

java - 分而治之算法 [字符数组]

c - 难以理解的GCC汇编指令计算条件跳转

c - 宏 foo(a,b, ;) 的含义

C/Cygwin : Porting htoll() from macOS/unix to Windows Cygwin

c# - 为什么 char 数组在控制台上显示内容,而 string 和 int 数组不在 c# 中?

node.js - 我可以限制 Node.js/express.js 中 TLS 消息的长度吗?

c++ - lua - 在 C 中存储闭包,在 C 中调用异步