c - 将 char * 数组设置为单个字符串 C

标签 c arrays string pointers

我希望你能帮我解决这个问题。我有一个字符指针数组,我想保存唯一的字符串。我有一个返回 char 指针的方法,并且我将此函数的返回值设置为递增数组中的值:

// array to hold strings    
char * finalStack[STR_LEN] = {""};

// returns char * to store in array
char * generateStackFrame (char stackVals[]) {
   static char buffer[BUF_LEN];
   int index = 0;
   // 8 bytes
   if (stackVals[0] == stackVals[1] == stackVals[2] == stackVals[3]) {
       snprintf (buffer, sizeof(buffer), "|       %c       |", stackVals[0]);
   // 4 bytes + padding
   } else {
       for (index = 0; index < 4; index++) {
           if (stackVals[index] == '\0')
               stackVals[index] = 'X';
       }
       snprintf (buffer, sizeof(buffer), "| %c | %c | %c | %c |",
                 stackVals[3], stackVals[2], stackVals[1], stackVals[0]);
   }
   return buffer;
}

该方法的调用方式如下:

...
    finalStack[index] =  generateStackFrame (stackVals);
...

我有一个循环,它生成不同的值,然后调用该方法并将结果设置为 char * 数组中的索引。这适用于第一个值,但对于每个连续值,即使我将新的 char * 设置为数组中的下一个位置,它也会将数组中的所有值设置为当前字符串。我猜这是一个明显的错误,也许我没有完全理解这里发生的概念。

感谢您的帮助!

最佳答案

您在函数中使用static char buffer[BUF_LEN];。关键字static确保每个函数调用都使用相同的空间。因此,当您在函数外部顺序设置值时,它们最终将指向同一空间。基本上数组中的所有索引最后都会指向同一个字符串。

为了解决这个问题,每次都分配新的内存

char * generateStackFrame (char stackVals[]) {
    char* buffer;
    buffer = malloc(sizeof(char)*BUF_LEN);
    ///rest of code

   return buffer;
}

注意-不要使用堆栈变量,因为从函数调用返回后它会丢失,使用malloc在堆上分配内存

char * generateStackFrame (char stackVals[]) {
    char buffer[BUF_LEN];  //this is wrong

关于c - 将 char * 数组设置为单个字符串 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23486441/

相关文章:

java - 从java字符串中高效提取数字(已经尝试过 Guava 和正则表达式)

Cython - 正确声明 C 函数

c - 带有通用文件的多个可执行文件的 Makefile

c# - 如何进行 Windows 驱动程序签名?

c - 如何拆分大型.a静态库?

java - 如何获取某个数组元素的键?

PHP 将多个数组分配给 $_SESSION

javascript - HTML 选择元素中对象数组的多个 Angular 过滤器

c# - 如何在 C# 中将不可读的字符串转换回 UTF-8 字节

java - 类型不匹配 : cannot convert from java. lang.String 到 String