char *img_name与char img_name[]的区别

本文探讨了在MFC应用程序中使用按钮消息响应时,如何正确地处理字符串连接问题。详细介绍了char数组与char指针的区别,并给出了避免程序崩溃的具体解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在MFC的按钮消息响应中写如下代码:

(1)char img_name[100]="..\\dataset\\holidays\\images\\";

(2)const char *src=result[k];
(3)strcat(img_name,src);
(4)IplImage *img=cvLoadImage(img_name);

点击按钮,程序正确运行。

而如果我将上面(1)作如下修改:

char  *img_name="..\\dataset\\holidays\\images\\";

点击按钮,程序崩了。经查资料在stackoverflow上找到答案的,http://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string。

原因就是:

一、char *img_name="..\\dataset\\holidays\\images\\" 中的img_name指向的字符串是不能被修改的,img_name是一个4字节或者8字节的内存,其内容是一个地址,sizeof(img_name)=4(Win32),sizeof(img_name)=8(x64);

二、char img_name[]是一个连续内存中的第一个地址,其内容是一个字符,如char str[]="hello",str是一个大小为6的char 型数组,由h,e,l,l,o和\0对其进行初始化。

解决方案:

引入一个copy的指针temp_img_name,修改代码如下:

(1)char  img_name[100]="..\\dataset\\holidays\\images\\";

(2)char *temp_img_name=NULL;

(3)temp_img_name=img_name;

(4)const char *src=result[k];
(5)strcat(temp_img_name,src);
(6)IplImage *img=cvLoadImage(temp_img_name);




/** * @struct RKLLMExtendParam * @brief The extend parameters for configuring an LLM instance. */ typedef struct { int32_t base_domain_id; /**< base_domain_id */ uint8_t reserved[112]; /**< reserved */ } RKLLMExtendParam; /** * @struct RKLLMParam * @brief Defines the parameters for configuring an LLM instance. */ typedef struct { const char* model_path; /**< Path to the model file. */ int32_t max_context_len; /**< Maximum number of tokens in the context window. */ int32_t max_new_tokens; /**< Maximum number of new tokens to generate. */ int32_t top_k; /**< Top-K sampling parameter for token generation. */ float top_p; /**< Top-P (nucleus) sampling parameter. */ float temperature; /**< Sampling temperature, affecting the randomness of token selection. */ float repeat_penalty; /**< Penalty for repeating tokens in generation. */ float frequency_penalty; /**< Penalizes frequent tokens during generation. */ float presence_penalty; /**< Penalizes tokens based on their presence in the input. */ int32_t mirostat; /**< Mirostat sampling strategy flag (0 to disable). */ float mirostat_tau; /**< Tau parameter for Mirostat sampling. */ float mirostat_eta; /**< Eta parameter for Mirostat sampling. */ bool skip_special_token; /**< Whether to skip special tokens during generation. */ bool is_async; /**< Whether to run inference asynchronously. */ const char* img_start; /**< Starting position of an image in multimodal input. */ const char* img_end; /**< Ending position of an image in multimodal input. */ const char* img_content; /**< Pointer to the image content. */ RKLLMExtendParam extend_param; /**< Extend parameters. */ } RKLLMParam; /** * @struct RKLLMLoraAdapter * @brief Defines parameters for a Lora adapter used in model fine-tuning. */ typedef struct { const char* lora_adapter_path; /**< Path to the Lora adapter file. */ const char* lora_adapter_name; /**< Name of the Lora adapter. */ float scale; /**< Scaling factor for applying the Lora adapter. */ } RKLLMLoraAdapter; /** * @struct RKLLMEmbedInput * @brief Represents an embedding input to the LLM. */ typedef struct { float* embed; /**< Pointer to the embedding vector (of size n_tokens * n_embed). */ size_t n_tokens; /**< Number of tokens represented in the embedding. */ } RKLLMEmbedInput;转换为node代码
03-09
int main(int argc, char** argv) { cudaSetDevice(DEVICE); std::string wts_name = ""; std::string engine_name = ""; bool is_p6 = false; float gd = 0.0f, gw = 0.0f; //std::string img_dir; if (!parse_args(argc, argv, wts_name, engine_name, is_p6, gd, gw)) { std::cerr << "arguments not right!" << std::endl; std::cerr << "./yolov5_det -s [.wts] [.engine] [n/s/m/l/x/n6/s6/m6/l6/x6 or c/c6 gd gw] // serialize model to plan file" << std::endl; std::cerr << "./yolov5_det -d [.engine] ../samples // deserialize plan file and run inference" << std::endl; return -1; } // create a model using the API directly and serialize it to a stream if (!wts_name.empty()) { IHostMemory* modelStream{ nullptr }; APIToModel(BATCH_SIZE, &modelStream, is_p6, gd, gw, wts_name); assert(modelStream != nullptr); std::ofstream p(engine_name, std::ios::binary); if (!p) { std::cerr << "could not open plan output file" << std::endl; return -1; } p.write(reinterpret_cast<const char*>(modelStream->data()), modelStream->size()); modelStream->destroy(); return 0; } // deserialize the .engine and run inference std::ifstream file(engine_name, std::ios::binary); if (!file.good()) { std::cerr << "read " << engine_name << " error!" << std::endl; return -1; } char *trtModelStream = nullptr; size_t size = 0; file.seekg(0, file.end); size = file.tellg(); file.seekg(0, file.beg); trtModelStream = new char[size]; assert(trtModelStream); file.read(trtModelStream, size); file.close(); // std::vector<std::string> file_names; // if (read_files_in_dir(img_dir.c_str(), file_names) < 0) { // std::cerr << "read_files_in_dir failed." << std::endl; // return -1; // } static float prob[BATCH_SIZE * OUTPUT_SIZE]; IRuntime* runtime = createInferRuntime(gLogger); assert(runtime != nullptr); ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size); assert(engine != nullptr); IExecutionContext* context = engine->createExecutionContext(); assert(context != nullptr); delete[] trtModelStream; assert(engine->getNbBindings() == 2); float* buffers[2]; // In order to bind the buffers, we need to know the names of the input and output tensors. // Note that indices are guaranteed to be less than IEngine::getNbBindings() const int inputIndex = engine->getBindingIndex(INPUT_BLOB_NAME); const int outputIndex = engine->getBindingIndex(OUTPUT_BLOB_NAME); assert(inputIndex == 0); assert(outputIndex == 1); // Create GPU buffers on device CUDA_CHECK(cudaMalloc((void**)&buffers[inputIndex], BATCH_SIZE * 3 * INPUT_H * INPUT_W * sizeof(float))); CUDA_CHECK(cudaMalloc((void**)&buffers[outputIndex], BATCH_SIZE * OUTPUT_SIZE * sizeof(float))); // Create stream cudaStream_t stream; CUDA_CHECK(cudaStreamCreate(&stream)); uint8_t* img_host = nullptr; uint8_t* img_device = nullptr; // prepare input data cache in pinned memory CUDA_CHECK(cudaMallocHost((void**)&img_host, MAX_IMAGE_INPUT_SIZE_THRESH * 3)); // prepare input data cache in device memory CUDA_CHECK(cudaMalloc((void**)&img_device, MAX_IMAGE_INPUT_SIZE_THRESH * 3)); cv::VideoCapture capture("/media/builderx/UUI/tsy_work/rb002/REC/2024_01_17T14_46_37__stream0.mp4"); //cv::VideoCapture capture(0); cv::Mat frame; int fcount = 0;帮我分析一下每行代码都是什么意思
03-08
int main(int argc, char** argv) { cudaSetDevice(DEVICE); std::string wts_name = ""; std::string engine_name = ""; bool is_p6 = false; float gd = 0.0f, gw = 0.0f; std::string img_dir; if (!parse_args(argc, argv, wts_name, engine_name, is_p6, gd, gw, img_dir)) { std::cerr << "arguments not right!" << std::endl; std::cerr << "./yolov5_det -s [.wts] [.engine] [n/s/m/l/x/n6/s6/m6/l6/x6 or c/c6 gd gw] // serialize model to plan file" << std::endl; std::cerr << "./yolov5_det -d [.engine] ../samples // deserialize plan file and run inference" << std::endl; return -1; } // create a model using the API directly and serialize it to a stream if (!wts_name.empty()) { IHostMemory* modelStream{ nullptr }; APIToModel(BATCH_SIZE, &modelStream, is_p6, gd, gw, wts_name); assert(modelStream != nullptr); std::ofstream p(engine_name, std::ios::binary); if (!p) { std::cerr << "could not open plan output file" << std::endl; return -1; } p.write(reinterpret_cast<const char*>(modelStream->data()), modelStream->size()); modelStream->destroy(); return 0; } // deserialize the .engine and run inference std::ifstream file(engine_name, std::ios::binary); if (!file.good()) { std::cerr << "read " << engine_name << " error!" << std::endl; return -1; } char *trtModelStream = nullptr; size_t size = 0; file.seekg(0, file.end); size = file.tellg(); file.seekg(0, file.beg); trtModelStream = new char[size]; assert(trtModelStream); file.read(trtModelStream, size); file.close(); std::vector<std::string> file_names; // if (read_files_in_dir(img_dir.c_str(), file_names) < 0) { // std::cerr << "read_files_in_dir failed." << std::endl; // return -1; // } static float prob[BATCH_SIZE * OUTPUT_SIZE]; IRuntime* runtime = createInferRuntime(gLogger); assert(runtime != nullptr); ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size); assert(engine != nullptr); IExecutionContext* context = engine->createExecutionContext(); assert(context != nullptr); delete[] trtModelStream; assert(engine->getNbBindings() == 2); float* buffers[2]; // In order to bind the buffers, we need to know the names of the input and output tensors. // Note that indices are guaranteed to be less than IEngine::getNbBindings() const int inputIndex = engine->getBindingIndex(INPUT_BLOB_NAME); const int outputIndex = engine->getBindingIndex(OUTPUT_BLOB_NAME); assert(inputIndex == 0); assert(outputIndex == 1); // Create GPU buffers on device CUDA_CHECK(cudaMalloc((void**)&buffers[inputIndex], BATCH_SIZE * 3 * INPUT_H * INPUT_W * sizeof(float))); CUDA_CHECK(cudaMalloc((void**)&buffers[outputIndex], BATCH_SIZE * OUTPUT_SIZE * sizeof(float))); // Create stream cudaStream_t stream; CUDA_CHECK(cudaStreamCreate(&stream)); uint8_t* img_host = nullptr; uint8_t* img_device = nullptr; // prepare input data cache in pinned memory CUDA_CHECK(cudaMallocHost((void**)&img_host, MAX_IMAGE_INPUT_SIZE_THRESH * 3));你现在是深度学习c++工程师,目标是修改一段代码使得这段代码可以直接检测视频,限制是不要啰嗦,代码尽量简单易懂
03-08
struct node { char path[1024]; struct node *next; struct node *prev; }; static const char * getenv_default(const char * name, const char * dflt) { return getenv(name) ?: dflt; } #if LV_USE_LINUX_FBDEV static void lv_linux_disp_init(void) { const char * device = getenv_default("LV_LINUX_FBDEV_DEVICE", "/dev/fb0"); lv_display_t * disp = lv_linux_fbdev_create(); lv_linux_fbdev_set_file(disp, device); } #elif LV_USE_LINUX_DRM static void lv_linux_disp_init(void) { const char * device = getenv_default("LV_LINUX_DRM_CARD", "/dev/dri/card0"); lv_display_t * disp = lv_linux_drm_create(); lv_linux_drm_set_file(disp, device, -1); } #elif LV_USE_SDL static void lv_linux_disp_init(void) { const int width = atoi(getenv("LV_SDL_VIDEO_WIDTH") ?: "800"); const int height = atoi(getenv("LV_SDL_VIDEO_HEIGHT") ?: "480"); lv_sdl_window_create(width, height); } #else #error Unsupported configuration #endif lv_obj_t *btn; lv_obj_t *btn1; lv_obj_t *btn2; lv_obj_t *btn3; struct node *pos = NULL; struct node * up_showpic(){ lv_obj_t *img1 = lv_image_create(lv_screen_active()); pos = pos -> prev; char path[1024]; char ch = 'A'; sprintf(path,"%c:%s",ch,pos->path); lv_image_set_src(img1,path); return pos; } struct node * down_showpic(){ lv_obj_t *img1 = lv_image_create(lv_screen_active()); pos = pos -> next; char path[1024]; char ch = 'A'; sprintf(path,"%c:%s",ch,pos->path); lv_image_set_src(img1,path); return pos; } static void button_cb(lv_event_t *e){ void *obj = lv_event_get_target(e); printf("按钮被点击%p\n",obj); struct node*pos = NULL; if(btn == obj){ printf("往上切换图片\n"); pos = up_showpic(); } else if(btn1 == obj){ printf("往下切换图片\n"); pos = down_showpic(); } else if(btn2 == obj){ lv_obj_t *img1 = lv_image_create(lv_screen_active()); char path[1024]; char ch = 'A'; sprintf(path,"%c:%s",ch,pos->path); printf("放大图片\n"); lv_image_set_scale(path,256); } else if(btn3 == obj){ printf("缩小图片\n"); } }放大图片时为什么会段错误
03-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linda Fan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值