修改char*array [x] [y]

Wul*_*lpo 0 c arrays pointers

如何在二维数组中修改(增加ASCII值)每个字符char *

我现在有这个代码:

int riadky = 2;
int stlpce = 7;

char* x[riadky][stlpce];

int i,j;
for ( i = 0; i < riadky; i++)
    for (j = 0; j < stlpce; j++)
        x[i][j] = "test";

x[0][1] = "something";

for ( i = 0; i < riadky; i++){
    for (j = 0; j < stlpce; j++){
        printf("%s ", x[i][j]);
    }
        printf("\n");
}
printf("\n");

char * temp;
for ( i = 0; i < riadky; i++) {
    for (j = 0; j < stlpce; j++) {
        for (temp= x[i][j]; *temp; temp++) {
            (*temp)++;            //segmentation fault
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它会与注释一起分段.


我试试这个,但仍然......分段愚蠢

char ***alloc_array(int x, int y) {
    char ***a = calloc(x, sizeof(char **));
    int i;
    for(i = 0; i != x; i++) {
        a[i] = calloc(y, sizeof(char *));
    }
    return a;
}

int main() {

    int riadky = 3;
    int stlpce = 7;
    char ***x = alloc_array(riadky, stlpce);

    int i,j;
    for ( i = 0; i < riadky; i++){
        for (j = 0; j < stlpce; j++){
            strcpy(x[i][j],"asdasd");
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Nis*_*röm 6

for ( i = 0; i < riadky; i++)
  for (j = 0; j < stlpce; j++)
    x[i][j] = "test";

x[0][1] = "something";
Run Code Online (Sandbox Code Playgroud)

您正在初始化指针以指向字符串文字.允许(但不要求)编译器将字符串文字放在只读存储器中.尝试修改其中一个可能会导致分段错误.

您需要为字符串分配动态内存:

#include <stdlib.h>

...

for (...) {
  for (...) {
    x[i][j] = malloc (strlen (somestring)+1);
    if (x[i][j]) {
      strcpy (x[i][j], somestring);
    } else {
      /* Allocation error */
    }
Run Code Online (Sandbox Code Playgroud)

where somestring是字符串文字或包含要存储的字符串的变量.如果您以后需要存储更大的字符串,则需要realloc()指点.free()完成使用后,不要忘记指针.

我注意到你已经编辑了你的帖子以包含对同一问题的另一次尝试,这次使用动态分配的数组而不是静态数组.但是你仍然没有为实际的字符串分配任何内存,只是一个指针数组.对于两个版本的代码,我的答案应该保持不变.