Created
July 7, 2018 01:15
-
-
Save toVersus/2b7ea27750eeb4d813f9259ffd70c3d5 to your computer and use it in GitHub Desktop.
concat two strings using raw poitners
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate nix; | |
use std::ffi::CString; | |
use std::ptr::write; | |
use nix::libc::{free, malloc, strlen}; | |
fn main() { | |
let c_str1 = CString::new("Hello, ").unwrap(); | |
let c_str2 = CString::new("world!").unwrap(); | |
let str1_ptr = c_str1.into_raw(); | |
let str2_ptr = c_str2.into_raw(); | |
let str1_len = unsafe { strlen(str1_ptr) }; | |
let str2_len = unsafe { strlen(str2_ptr) }; | |
let a_ptr = unsafe { malloc(str1_len + str2_len + 1) }; | |
let a = a_ptr as *mut i8; | |
for i in 0..str1_len { | |
unsafe { write(a.add(i), *(str1_ptr.add(i))) }; | |
} | |
for i in 0..str2_len { | |
unsafe { write(a.add(str1_len).add(i), *(str2_ptr.add(i))) }; | |
} | |
let hello = unsafe { CString::from_raw(a) }; | |
println!("{}", hello.to_str().unwrap()); | |
unsafe { free(a_ptr) }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment