[英]C++ - How do i put a whole char-array in a pointer?
I´ma beginner (and didn´t find an answer on the internet).我是初学者(并没有在互联网上找到答案)。 I got a pointer and a char array and want to save the entire Array, not only the first element, in a pointer to give it to a function (also, im not allowed to change the function parameters).
我有一个指针和一个字符数组,并且想要保存整个数组,而不仅仅是第一个元素,保存在一个指针中以将其提供给一个函数(另外,我不允许更改函数参数)。
char Feld[ ] = {1,2,3}
char *pointer = NULL;
pointer = ???
function:功能:
void strncat(char *s)
{...}
Call function:调用函数:
strncat(???)
Thank you for your help感谢您的帮助
If the function is declared the following way如果函数声明如下
void strncat(char *s);
then it means that the function does no know the size of the array pointed to by the pointer s
.那么这意味着该函数不知道指针
s
指向s
数组的大小。 So it seems the function deals with a string: a sequence of characters terminated by a zero character.所以看起来这个函数处理的是一个字符串:一个以零字符结尾的字符序列。
On the other hand, using the letter 'n'
in the function name strncat
means that the function should have one more parameter that specifies the length of the used character array.另一方面,在函数名
strncat
使用字母'n'
意味着该函数应该有一个更多的参数来指定所用字符数组的长度。
So either the function is declaraed incorrectly or it should be renamed as for example所以要么函数声明不正确,要么应该重命名为例如
void strcat(char *s);
Or it is better to declare it like或者最好将其声明为
char * strcat(char *s);
Hence this declaration of a character array因此这个字符数组的声明
char Feld[ ] = {1,2,3};
can not be used in the function because the array does not contain a string and its length is not passed to the function.不能在函数中使用,因为数组不包含字符串且其长度未传递给函数。
You should declare the array for example like您应该声明数组,例如
char Feld[ ] = { '1','2','3', '\0' };
or like或喜欢
char Feld[ ] = "123"; // or { "123" }
Pointers do not keep the information whether they point to a single object or the first element of an array.指针不保留它们指向单个对象还是数组的第一个元素的信息。
So if the function is declared as shown above then you should just write因此,如果函数声明如上所示,那么您应该只写
char *p = Feld;
strcat( p );
or without using the intermediate pointer like或不使用中间指针,如
strcat( Feld );
Within the function the length of the string will be determinate by the number of characters before the terminating zero '\\0'
.在函数内,字符串的长度将由终止零
'\\0'
之前的字符数确定。
Feld
is a pointer to the first element of the Array. Feld
是指向数组第一个元素的指针。 So you can pass strncat(Feld)
.所以你可以通过
strncat(Feld)
。 If you want you can also do char* pointer = Feld;
如果你愿意,你也可以做
char* pointer = Feld;
and strncat(pointer)
but there's really no need for that.和
strncat(pointer)
但真的没有必要。 You can then access the other elements with s[0],s[1],s[2]
.然后,您可以使用
s[0],s[1],s[2]
访问其他元素。 As @Vlad pointed out you can't assign integers to a char array rather you need to do char Feld[ ] = {'1','2','3'}
正如@Vlad 指出的那样,您不能将整数分配给 char 数组,而需要执行
char Feld[ ] = {'1','2','3'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.