简体   繁体   中英

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 . 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.

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' .

Feld is a pointer to the first element of the Array. So you can pass strncat(Feld) . If you want you can also do char* pointer = Feld; and strncat(pointer) but there's really no need for that. You can then access the other elements with 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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM