簡體   English   中英

strcpy 和 strcat 在 c 中返回錯誤

[英]strcpy and strcat return an error in c

   char first[]="aa";               
   strcat(first,ar[0]);

   char *second[10];   
   strcpy(second[0],first);

我想使用 strcat 和 strcpy。 strcat 有效,但 strcpy 中存在錯誤。 我該如何修改它?

在 C 中,基本上有三種字符串/字符數組變量:

  1. 字符串常量指針
  2. 在編譯時設置長度的字符數組
  3. 在運行時設置長度的動態字符數組。

對於動態數組,它使用的內存在程序運行時被保留。 下面的程序說明了三種不同的情況。 它還為內存分配提供了一個方便的宏。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NEW_ARRAY(ptr, n) \
    { \
        (ptr) = malloc((n) * sizeof (ptr)[0]); \
        if ((ptr) == NULL) { \
            fprintf(stderr, "error: Memory exhausted\n"); \
            exit(EXIT_FAILURE); \
        } \
    }

int main(void)
{
    const char *s1 = "foo";
    char s2[4] = "bar";
    char *s3;

    NEW_ARRAY(s3, 4);
    strcpy(s3, "baz");

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM