2013-03-10 80 views
0

我正在從套接字讀取緩衝區字節,但我不知道如何用長度信息初始化緩衝區數組。用變量初始化緩衝區數組的長度

uint32_t len; 
int lengthbytes = 0; 
int databytes = 0; 

// receive the length info of an image data 
lengthbytes = recv(clientSocket, (char *)&len, sizeof(len), 0); 

// convert hexadecimal data to length in bytes 
len = ntohl(len); 

// ????? how to initialize the buffer array with the length info ???? 
char buf[len]; -----> this is illegal in C 

// read the image data 
databytes = recv(clientSocket, buf, sizeof(buf), 0); 

回答

2

當您聲明buf時,您聲明瞭一個可變長度數組。這在C中是合法的(來自C99標準),但在C++中是非法的。在C++中,你可以改用std::vector

std::vector<char> buf(len); 

你可以使用這個載體在調用recv還有:

databytes = recv(clientSocket, &buf[0], buf.size(), 0); 

要使用循環中的載體,你有兩個選擇:

  1. 聲明循環外部的變量,並使用需要3210和resize時:

    std::vector<char> buf; 
    
    // ... 
    
    for (int i = 0; i < number_of_images; i++) 
    { 
        std::cout << "Fetching image #" << (i + 1) << '\n'; 
    
        // Get the image length 
        size_t length = get_image_length(); 
    
        buf.clear(); // Clear the buffer 
        buf.resize(length); // Set the size to the image length 
    
        // Receive the image 
        databytes = recv(clientSocket, &buf[0], buf.size(), 0); 
    } 
    
  2. 聲明矢量是在循環內本地:

    for (int i = 0; i < number_of_images; i++) 
    { 
        std::cout << "Fetching image #" << (i + 1) << '\n'; 
    
        // Get the image length 
        size_t length = get_image_length(); 
    
        std::vector<char> buf(length); 
    
        // Receive the image 
        databytes = recv(clientSocket, &buf[0], buf.size(), 0); 
    } 
    
+0

如果我想使用while循環來接收許多圖像,如何在每個循環結束時刪除'buf'的內容? – askingtoomuch 2013-03-12 11:45:33

+0

@boogiedoll請參閱我的更新回答。 – 2013-03-12 12:18:20

+0

太棒了!謝謝 :) – askingtoomuch 2013-03-12 13:47:41

4
len = ntohl(len); 
char buf[len]; //----> this is illegal in C 

這是有效的在C99,它被稱爲一個可變長度數組。如果您未使用C99,請使用malloc分配數組(並聲明bufchar *)。

1

你必須使用動態內存分配;

char* buf = new char[len]; 

如果您使用buf完成後,不要忘記調用delete釋放內存。

delete[] buf; 
1

請通過malloc分配緩衝區即buf = malloc(sizeof(char) * len);

1

你可以用新的或malloc的做到這一點。 不要忘記完成後刪除緩衝區!

1

可以使用一個std::vector<char>,然後使用它的data()作爲數組緩衝液:

#include <vector> 
std::vector<char> buf(len); 
databytes = recv(clientSocket, buf.data(), buf.size(), 0); // access underlying char array 
databytes = recv(clientSocket, &buf[0], buf.size(), 0); // as above, C++03 version 
1

我寫了一個叫的類正是爲了這個目的在C++中。

你可以在這裏找到:
small_lib.cpp
small_lib.h

這兩個文件是MIT許可,所以你可以使用它無論如何你喜歡。

如何使用這個類?

tempbuf buf(len); 
databytes = recv(clientSocket, buf.get(), buf.size(), 0); // if you want char* returned 
databytes = recv(clientSocket, buf.constchar(), buf.size(), 0); // if you want constchar* returned 

你猜我爲什麼寫這個課?您不需要刪除或取消分配動態分配的內存,因爲它是在類的析構函數中完成的。

爲什麼我沒有使用std::auto_ptr?因爲根據我的理解,這隻適用於非數組,因爲它支持new X而不是new X[10]