简体   繁体   English

修改char * array [x] [y]

[英]Modify char *array[x][y]

How can I modify (increase ASCII value) each char in a two dimensional array of char * ? 如何修改char *二维数组中的每个char(增加ASCII值)?

I have this code now: 我现在有以下代码:

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
        }
    }
}

When I run it, it segfaults on the line with the comment. 当我运行它时,它会在注释行中出现段错误。


I try this, but still... segmentation falult 我尝试了这个,但仍然...细分失败

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;
}
 for ( i = 0; i < riadky; i++) for (j = 0; j < stlpce; j++) x[i][j] = "test"; x[0][1] = "something"; 

You are initializing your pointers to point to string literals. 您正在初始化指向字符串文字的指针。 The compiler is allowed (but not required to) place string literals in read-only memory. 允许(但不要求)编译器将字符串文字放置在只读存储器中。 An attempt to modify one of them is likely to result in a segmentation fault. 尝试修改其中之一可能会导致分段错误。

You need to allocate dynamic memory for your strings: 您需要为字符串分配动态内存:

#include <stdlib.h>

...

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

where somestring is a string literal or a variable containing the string you want to store. 其中somestring是字符串文字或包含要存储的字符串的变量。 If you later need to store larger strings, you will have to realloc() your pointers. 如果以后需要存储较大的字符串,你将不得不realloc()您的指针。 Don't forget to free() your pointers when you are done using them. 使用完指针后,不要忘记free()指针。

I noticed that you have edited your post to include another attempt at the same problem, this time using dynamically allocated arrays rather than static arrays. 我注意到您已经编辑了帖子,以包含针对同一问题的另一次尝试,这次使用动态分配的数组而不是静态数组。 But you still haven't allocated any memory for the actual strings, just an array of pointers. 但是您仍然没有为实际的字符串分配任何内存,只是分配了一个指针数组。 My answer should work unchanged for both versions of your code. 对于您的两个版本的代码,我的答案都应保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM