char *str_array[3]; char str1[] = "Hello"; char str2[] = "World"; char str3[] = "!"; str_array[0] = &str1; str_array[1] = str2; str_array[2] = str3;出现type specifier missing, defaults to 'int'
时间: 2024-01-25 14:04:32 浏览: 25
在你的代码中,`&str1`是一个指向字符数组的地址,而`str_array`数组的元素是指向字符的指针。因此,你应该将`str1`的地址直接赋值给`str_array[0]`元素,而不是使用取地址符`&`。另外,由于`str2`和`str3`都是字符数组,它们的名字就是一个指向字符的指针,因此不需要使用取地址符`&`。
因此,你的代码应该改为:
```C
char *str_array[3];
char str1[] = "Hello";
char str2[] = "World";
char str3[] = "!";
str_array[0] = str1;
str_array[1] = str2;
str_array[2] = str3;
```
这样就可以正确地定义一个字符串指针数组,并把三个字符串赋值给它的元素。
相关问题
char *str_array[3]; char str1[] = "Hello"; char str2[] = "World"; char str3[] = "!"; str_array[0] = str1; str_array[1] = str2; str_array[2] = str3;出现type specifier missing, defaults to 'int'
这个错误通常是因为你的代码放在了函数外面,而不是在函数内部。在C语言中,只有变量声明和定义可以放在函数外面,而赋值语句必须放在函数内部。
如果你把上述代码放在一个函数内部,就不会出现这个错误了。例如:
```C
#include <stdio.h>
int main() {
char *str_array[3];
char str1[] = "Hello";
char str2[] = "World";
char str3[] = "!";
str_array[0] = str1;
str_array[1] = str2;
str_array[2] = str3;
// 打印字符串数组的内容
for (int i = 0; i < 3; i++) {
printf("%s\n", str_array[i]);
}
return 0;
}
```
这个例子定义了一个字符串指针数组`str_array`,并将三个字符串赋值给它的元素。然后使用循环打印出字符串数组的内容。在函数内部,你可以自由地定义变量、赋值和使用它们。
c语言char* 转换字节数组
可以使用memcpy函数将char*类型转换为字节数组。具体实现如下:
```c
char* str = "hello world";
int len = strlen(str);
unsigned char* byte_array = (unsigned char*)malloc(len);
memcpy(byte_array, str, len);
```
这段代码中,我们先定义了一个char*类型的字符串str,然后使用strlen函数获取它的长度len。接着,我们使用malloc函数为字节数组分配内存空间,大小为len。最后,使用memcpy函数将字符串复制到字节数组中。
需要注意的是,由于C语言中char类型是有符号的,而字节数组通常是无符号的,因此我们将byte_array定义为unsigned char*类型。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)