简体   繁体   中英

Dumb questions: strcat and char pointers

I am usually not using pointer chars when working with strings but I usually think they are better in the sense that I can print the whole string without iterating each character.

Anyway since I don't use them I don't really know how these two interact. When running the following code the program crashes, so I've got no clue what to do since there's no error.

int main(){
char s[]="abcde";
char *p;
for(unsigned int i=0;i<strlen(s);i++)
    strcat(p,s+i);
cout<<*p;
}

I tried representing both strings as pointers and it didn't change anything. It crashes only if I try to print the second array. I tried *p++=*s or something similar I've found on google but it still crashes, what am I doing wrong?

Pointer p points nowhere, you need to reserve memory for the second array. For example,

char *p = new char [strlen(s) + 1];

Also strcat in a for loop is not the best way to copy a string. Try

strcpy(p, s);

(after allocating memory to p, of course).

Addition: If you need to use strcat instead of strcpy , you need to initialize string p with empty string, that is:

char *p = new char [strlen(s) + 1];
*p = '\0';

You are not allocating memory to a pointer p. When you call strcat without allocating memory of course you will get segmentation fault since strcat will try to write to a memory pointer by the pointer p.

You don't need a for loop for concatenating strings. strcat function does full string copying to memory pointed by p.

If you want print whole string don't deference pointer p fi you want print the whole string, deferencing results in printing only the first character of a string.

#include<iostream>
#include<cstring>

int main(){
char s[]="abcde";
//Allocating memory to so that p points valid memory.
char concatenatedString[50] = "";
//Initializing pointer to allocated memory.
char *p = concatenatedString;
// for(unsigned int i = 0;i < strlen(s); i++) //Not required.
    strcat(p,s);
//Here don't dereference if you want to print whole string.
std::cout<<p;
} 

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