Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于传参的一个问题 #1

Open
andy27182 opened this issue Dec 25, 2024 · 1 comment
Open

关于传参的一个问题 #1

andy27182 opened this issue Dec 25, 2024 · 1 comment

Comments

@andy27182
Copy link

cc array test 01

函数cc_array_set的原型中最后一个参数是void *用于传递任意数据类型指针,在实际创建内存的时候,使用了memcpy将立即数所指向的内存复制到新内存中,配套如下测试代码是好理解的:

	for (i = 0.27; i < 10; i++)
		assert(!cc_array_set(&array, i, &i));

但是在阅读cc list map test 01代码时,有了些许困惑:

	assert(!cc_list_map_set(map, (void *)1, (void *)'a', NULL));
	assert(!cc_map_set(map, (void *)2, (void *)'b', NULL));
	assert(!cc_map_set(map, (void *)9, (void *)'c', NULL));

根据cc_list_map_set的实现可知,是将void *key直接赋值为了(void *)1,即将0x00000001视为一个地址并视为键值进行了存储,(void *)'a'则是将字符串常量首地址存入void *value,这个字符串常量在跳出函数体后是不是会被系统回收而导致错误?c99似乎是有语法糖可以对立即数进行取址的,再内部创建新的内存,并使用memcpy是不是更为稳妥?

@wallacegibbon
Copy link
Owner

@andy27182 我觉得换一个思路会更顺畅,void* 不要理解成指针,理解成 “任意机器字长的值” 比较好。这里的 (void*)1 只是为了表示 1 这个值,强转是为了应付编译器。同理 (void*)'b' 也只是为了使用 'b' 这个值。并不涉及到指针。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants