C语言学习018:strdup复制字符串数组

时间:2022-07-29 18:28:51

  在C语言学习005:不能修改的字符串中我们知道字符串是存储在常量区域的,将它赋值给数组实际是将常量区的字符串副本拷贝到栈内存中,如果将这个数组赋值给指针,我们可以改变数组中的元素,就像下面那样

 int main(){
char s[]="hello c";
char* temp=s;
temp[]='a';
temp[]='b';
printf("%s\n",s);
return ;
}

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAocAAAAbCAIAAACBTbKkAAACFklEQVR4nO3dW1LiQABA0SzCD40BN+BWSAiuzjzYw+gGXMM4C5qPSAsBYnBwmlDnFB8a8uhUUd7qrlgkaV6neXWXV3eL6nbxfLt4rn79vnkskiR525J8S3fg267w1sHt++/2Ng5fbn//kScfPmdv2CPPP7D/wCHfG+eYW7ic+/3y0gfPk4z+DEQZP8AZpMXRKk/CsT/BF+jCh3d2U7/fqY8fmKTPKufV3QSrnJxvTvmjJjHIM5r6/U59/MBUpUWdFnWa15swV5OrMgBcifuuysWmynlVv6gyAMQQqhwe+6rNlQEgivui7oXZXBkA4rhfNp9hzus0r1UZAOLIlk0X5jBdHq7ywIOpX/4/qMdZAWBIqHKYMdcv78Nz5eG+Djf7X4cLAFcsWzYfYV5+hFmVASCOrGw2Ye5XecyK9H5ox1f51JVtK+EAXLmsbLswh3XsZm+u3Avh9q/HWrt/oZNOMny4MANwnUKVw4y5OTRXvqgqA8B1mpVNVjZZ2YYwN6/vN4/FQDVVGQB+xBSrrNAAXKdZ2c66Rexyp8rJke+d7f2wH9pt47ePGeqp+wPAxMxWbRfmWdl2M+ZQZQDgv5qv2ln3UmUAiGu3yk1WqjIARDJftfNNlbtX8/pHlQEggs8qb9qsygAQx3y13glz2bZWsAEgilDlEObWXBkAolBlALgUD0/rh6f19jq2KgNAHL0qz1UZACL5C06XcNUkF2U9AAAAAElFTkSuQmCC" alt="" />  

  但是现在我们不想让指针可以修改字符串数组的中的元素,而又可以得到字符串中的元素,那么我么需要再拷贝一份字符串数组的元素的副本,然后把地址给到指针,就可以通过strdup实现

 int main(){
char s[]="hello c";
char* temp=strdup(s);
temp[]='a';
temp[]='b';
printf("%s\n",s);
return ;
}

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoUAAAAYCAIAAAADLBA3AAABaklEQVR4nO3cTU7CQBiA4TmTXkQPIJRr6GGg9RLiikvAWb7EmcYF/jSAtbJwIj7PikzopLs336Rtulu+3C3z07Zc3z4kAODXRUSaLfNsldd6DACVRESarfJslZ+2WY8BoIrPHpuPAaAWPQaA+iIizQc93rybvsVmYMo6AHAgItK8zfPBfHxeQb+6So8B4FvvPW71GACqGevxQUrHz5+nr//0HNu5NwAXb9/jctzjgyQPc3gyjRN7/O0+I5dLMgCXKiJS05Z5W06eVx/0eGRU/YUeA8CleutxM63HIxvpMQCc7Zwe15qPtRmASxURqen6pisn3z8+/n0cxc2R6etTbvGn/weAPyci0qLrm673fS4AqGXQ450eA0Ad+x6XRdc/73o9BoAq3uZjPQaAiiIiLR71GABq0mMAqO/zvHqtxwBQycf7x56vBoBqPp6vLutdub7RYwCoYP+9zNy0eb0tVzf3te8HAP6jiHgF7D5JpbbOH9EAAAAASUVORK5CYII=" alt="" />