char数组中的问题?

时间:2009-11-05 04:19:03

标签: c string arrays

char *funcNames[]= {"VString","VChar","VArray","VData"};

    for(int i=0;i<4;i++)
    {

        char* temp = funcNames[i];
        int len = strlen(funcNames[i]);
        for(int j = 0;j<len ;j++)
        {
            if(j!=0)
            {
                char arr = temp[j];
            }
        }
}

这里我想将“V”与char数组中的所有字符串分开...并在string的开头创建另一个没有“V”的char数组。我想要另一个char数组{String,char,array,data}。 ..我不能制作一个char数组....帮助我解决我的问题...

3 个答案:

答案 0 :(得分:5)

你真的需要副本吗?你可以创建一个指向原始字符串的新数组:

char *newArray[4];
for (i = 0; i < 4; i++) {
  newArray[i] = funcNames[i] + 1;
}

答案 1 :(得分:2)

数组和指针之间只有很小的差异所以我选择:

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

int main (void) {
    int i;
    char *funcNames[]= {"VString","VChar","VArray","VData"};

    // This is the code that dupicates your strings by allocating an array,
    //   then allocating each string within that array (and copying).
    // Note we use strlen, not strlen+1 to mallocsince we're replacing the
    //  'V' at the start with the zero byte at the end. Also we strcpy
    // from char offset 1, not 0 (to skip the fist char).

    char **newNames = malloc (sizeof(char*) * sizeof(funcNames) / sizeof(*funcNames));
    assert (newNames != NULL);
    for (i = 0; i < sizeof(funcNames) / sizeof(*funcNames); i++) {
        newNames[i] = malloc (strlen (funcNames[i]));
        assert (newNames[i] != NULL);
        strcpy (newNames[i], funcNames[i] + 1);
    }

    /* Use your newNames here */

    for (i = 0; i < sizeof(funcNames) / sizeof(*funcNames); i++) {
        printf ("funcNames[%d] @%08x = '%s'\n", i, funcNames[i], funcNames[i]);
        printf (" newNames[%d] @%08x = '%s'\n", i,  newNames[i],  newNames[i]);
        putchar ('\n');
    }

    // Finished using them.

    // Free the strings themselves, then free the array.

    for (i = 0; i < sizeof(funcNames) / sizeof(*funcNames); i++)
        free (newNames[i]);
    free (newNames);

    return 0;
}

您可以从输出中看到内存中变量的位置不同,并且新字符串的内容是您想要的内容:

funcNames[0] @00402000 = 'VString'
 newNames[0] @006601c0 = 'String'

funcNames[1] @00402008 = 'VChar'
 newNames[1] @006601d0 = 'Char'

funcNames[2] @0040200e = 'VArray'
 newNames[2] @006601e0 = 'Array'

funcNames[3] @00402015 = 'VData'
 newNames[3] @006601f0 = 'Data'

答案 2 :(得分:2)

如果确实需要制作副本,则必须使用动态分配来创建缓冲区来保存副本。你要做的是声明一个指针数组,并在每个数组的条目中放置一个分配的字符串缓冲区:

char *newArray[4];
for (i = 0; i < 4; i++) {
   newArray[i] = malloc(sizeof(char) * streln(funcNames[0]));
   strcpy(newArray[i], funcNames[i] + 1);
 }

您必须在每个分配的缓冲区上调用free()。​​

或者如果您不想进行分配并且知道funcNames中字符串的最大长度:

#define MAX_FUNC_NAME_LEN 32
char newArray[4][MAX_FUNC_NAME_LEN];
for (i = 0; i < 4; i++) {
   strcpy(newArray[i], funcNames[i] + 1);
 }