[英]C programming strcat using pointer
我是C的初學者。我想用指針創建strcat函數。 我做到了,但不知道它有什么問題。 我使用gcc編譯器,它給出了分段錯誤輸出。
#include<stdio.h>
#include<string.h>
char scat(char *,char *);
void main()
{
char *s="james";
char *t="bond";
char *q=scat(s,t);
while(*q!='\0') printf("the concatenated string is %c",*q);
}
char *scat(char *s,char *t)
{
char *p=s;
while(*p!='\0'){
p++;
}
while(*t!='\0'){
*p=*t;
p++;
t++;
}
return p-s-t;
}
這個工作:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *scat(char *,char *); /* 1: your prototype was wrong */
void main()
{
char *s="james";
char *t="bond";
char *q=scat(s,t);
printf("cat: %s\n", q); /* 2: you can use %s to print a string */
free(q);
}
char *scat(char *s,char *t)
{
char *p=malloc(strlen(s)+strlen(t)+1); /* 3: you will have to reserve memory to hold the copy. */
int ptr =0, temp = 0; /* 4 initialise some helpers */
while(s[temp]!='\0'){ /* 5. use the temp to "walk" over string 1 */
p[ptr++] = s[temp++];
}
temp=0;
while(t[temp]!='\0'){ /* and string two */
p[ptr++]=t[temp++];
}
return p;
}
你必須在s
的末尾分配新的空間來復制。 否則,你的廁所[將進入內存,你沒有訪問權限。
你應該在這里了解malloc()
。
修改字符串文字和s
是未定義的行為,並且最終p
指向字符串文字:
char* s = "james";
s
作為第一個參數傳遞給分配了本地char* p
scat()
,然后:
*p=*t;
在第一次調用時,它試圖將空字符覆蓋在字符串文字"james"
的末尾。
一個可能的解決方案是使用malloc()
來分配足夠大的緩沖區來包含兩個輸入字符串的連接:
char* result = malloc(strlen(s) + strlen(p) + 1); /* + 1 for null terminator. */
並將它們復制到其中。 調用者必須記住free()
返回的char*
。
您可能會發現常用的指針問題列表很有用。
因為p一直持續到字符串的末尾,然后它開始前進到非法內存。 這就是你得到分段錯誤的原因。
這是因為s指向“james \\ 0”,字符串文字並且你不能修改常量。
改變char *s="james";
to char s[50]="james";
。
你得到一個分段錯誤,因為你將指針移動到s
的末尾然后開始直接在s
將p
的數據寫入內存。 是什么讓你相信s
后有可寫的內存? 將數據寫入不可寫內存的任何嘗試都會導致分段錯誤,並且看起來s
后面s
內存不可寫(這是預期的,因為“字符串常量”通常存儲在只讀內存中)。
有些事情看起來不合時宜。
首先請記住,當你想要返回指向函數內創建的東西的指針時,它需要在某處進行malloc。 如果將目標作為參數傳遞給函數,則會容易得多。 如果您遵循前一種方法,請不要忘記在完成后將其free()
。
此外,函數scat必須返回聲明中的指針,即char *scat
,而不是char scat
。
最后你不需要那個循環來打印字符串printf("%s", string);
將為您打印字符串(如果它已終止)。
首先,由於以下行,您的代碼將處於infinte循環中。 你應該通過包含“p ++; t ++”語句來使用實心大括號。
while(*t!='\0')
*p=*t;
雖然你喜歡這樣,但是你試圖改變字符串文字的內容。 這將導致不確定的行為,如分段錯誤。
用雙引號括起來的字符序列稱為字符串文字。 它也被稱為“字符串”。 字符串的大小是固定的。 創建后,您無法擴展其大小並更改內容。 這樣做會導致未定義的行為。
要解決此問題,您需要分配一個新的字符數組,其大小是傳遞的兩個字符串長度的總和。 然后將兩個字符串附加到新數組中。 最后返回新數組的地址。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char* scat(char *,char *);
void append(char *t , char *s);
int main(void)
{
char *s="james";
char *t="bond";
char *n = scat(s,t);
printf("the concatenated string is %s",n);
return 0;
}
char* scat(char *s,char *t)
{
int len = strlen(s) + strlen(t);
char *tmp = (char *)malloc(sizeof(char)* len);
append(tmp,s);
append(tmp,t);
return tmp;
}
void append(char *t , char *s)
{
//move pointer t to end of the string it points.
while(*t != '\0'){
t++;
}
while( *s != '\0' ){
*t = *s;
t++;
s++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.