![](/img/trans.png)
[英]How to store characters into a char pointer using the strcpy() function
[英]How to copy an array of characters to a char pointer without using strcpy
我將如何在不手動使用 strcpy 的情況下將 char 數組的字符復制到 char 指針中。 例如:
char *Strings[NUM];
char temp[LEN];
int i;
for (i = 0; i < NUM; i++){
fgets(temp, LEN, stdin);
Strings[i] = malloc(strlen(temp)+1);
Strings[i] = temp; // What would go here instead of this,
// because this causes this to happen->
}
Input:
Hello
Whats up?
Nothing
Output (when the strings in the array of char pointers are printed):
Nothing
Nothing
Nothing
我不知道如何解決這個問題。
在您的示例中,您使用以下兩行:
Strings[i] = malloc(strlen(temp)+1); /* you should check return of malloc() */
Strings[i] = temp;
這是不正確的。 第二行只是覆蓋了從malloc()
返回的指針。 您需要改為使用<string.h>
strcpy()
:
Strings[i] = malloc(strlen(temp)+1);
strcpy(Strings[i], temp);
char *strcpy(char *dest, const char *src)
將指向的字符串從src
復制到dest
。dest
是目標,src
是要復制的字符串。 返回一個指向dest
的指針。
您也沒有檢查fgets()
返回,它在失敗時返回NULL
。 您還應該考慮刪除fgets()
附加的\\n
字符,因為您復制到Strings[i]
將有一個尾隨換行符,這可能不是您想要的。
由於另一個答案顯示了如何手動完成,您可能還需要考慮僅使用strdup()
為您進行復制。
strdup()
返回一個指向與字符串str重復的新字符串的指針。 內存從malloc()
獲得,並用free()
從堆中釋放。
這是一些執行額外錯誤檢查的示例代碼。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 3
#define BUFFSIZE 20
int main(void) {
char *strings[LEN] = {NULL};
char buffer[BUFFSIZE] = {'\0'};
size_t slen, strcnt = 0, i;
printf("Input:\n");
for (i = 0; i < LEN; i++) {
if (fgets(buffer, BUFFSIZE, stdin) == NULL) {
fprintf(stderr, "Error from fgets()\n");
exit(EXIT_FAILURE);
}
slen = strlen(buffer);
if (slen > 0 && buffer[slen-1] == '\n') {
buffer[slen-1] = '\0';
} else {
fprintf(stderr, "Too many characters entered\n");
exit(EXIT_FAILURE);
}
if (*buffer) {
strings[strcnt] = strdup(buffer);
if (strings[strcnt] == NULL) {
fprintf(stderr, "Cannot allocate buffer\n");
exit(EXIT_FAILURE);
}
strcnt++;
}
}
printf("\nOutput:\n");
for (i = 0; i < strcnt; i++) {
printf("%s\n", strings[i]);
free(strings[i]);
strings[i] = NULL;
}
return 0;
}
所以發生的事情是你改變了 temp 的值,但所有的指針都指向 temp 的一個實例。 您需要分配內存,然后手動復制數組。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int LEN = 20;
int NUM = 3;
char* Strings[NUM];
char temp[LEN];
int i,j;
for (i=0;i<NUM;i++){
fgets(temp,LEN,stdin);
Strings[i] = (char*)malloc(strlen(temp)+1);
for(j=0;j<=strlen(temp);j++) { /* this part */
if (j == strlen(temp))
Strings[i][j - 1] = temp[j]; /* overwrite \n with the terminating \0 */
else
Strings[i][j] = temp[j];
}
}
for (i=0;i<NUM;i++)
printf("%s\n", Strings[i]);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.