关于如何在C中连接char数组有很多问题,但是我想知道的与此不同。我想知道如何在C中连接“双指针” char数组。
例如,
const char *array1[] = {"aa", "bb"};
const char *array2[] = {"cc", "dd", "ee"};
我想像这样获得新的char双指针数组:
char **new_array = {"aa", "bb", "cc", "dd", "ee"};
// this code actually doesn't work, though
我想知道最简单,最快的方法。
编辑:实际上,我打算在下面创建一个程序。
int main(int argc, char **argv) {
pid_t pid;
char **args = {"sh", "-c"} + argv; // this code doesn't work
posix_spawn(&pid, "/bin/sh", NULL, NULL, (char* const*)args, NULL);
}
该程序只在“ sh -c”之后传递参数。
答案 0 :(得分:2)
当然,只需为此分配一个缓冲区
#define _GNU_SOURCE 1
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
const char * const array1[] = {"aa", "bb"};
const size_t array1_size = ARRAY_SIZE(array1);
const char * const array2[] = {"cc", "dd", "ee"};
const size_t array2_size = ARRAY_SIZE(array2);
const size_t concat_len = array1_size + array2_size;
const char ** const concat = malloc(concat_len * sizeof(*concat));
assert(concat != NULL);
for (size_t i = 0; i < concat_len; ++i) {
concat[i] = strdup(i < array1_size ? array1[i] : array2[i - array1_size]);
assert(concat[i] != NULL);
}
for (size_t i = 0; i < concat_len; ++i) {
printf("concat[%zu] = (%zu) '%s'\n", i, strlen(concat[i]), concat[i]);
}
for (size_t i = 0; i < concat_len; ++i) {
free(concat[i]);
}
free(concat);
return 0;
}
但是我们应该能够做得更好。
答案 1 :(得分:1)
class ImageUI {
private Context context;
private ArrayList<String> urls = new ArrayList<>();
private ImageView imageView;
private ProgressBar progressBar;
private LinearLayout linearLayoutScrollView;
public ImageUI(Context context, ArrayList<String> urls, LinearLayout linearLayoutScrollView) {
this.context = context;
this.urls = urls;
this.linearLayoutScrollView = linearLayoutScrollView;
}
private void buildUI() {
System.out.println("Error # 1");
imageView = new ImageView(context);
imageView.setVisibility(View.GONE);
System.out.println("Error # 2");
progressBar = new ProgressBar(context);
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.GONE);
System.out.println("Error # 3");
RelativeLayout relativeLayout = new RelativeLayout(context);
relativeLayout.setGravity(1);
relativeLayout.addView(imageView);
relativeLayout.addView(progressBar);
//
// System.out.println("Error # 4");
// linearLayoutScrollView = (LinearLayout) linearLayoutScrollView.findViewById(R.id.linearLayoutScrollView);
linearLayoutScrollView.addView(relativeLayout);
// System.out.println("Error # 5");
}
void downloadImages() {
int i = 0;
while (i < urls.size()) {
buildUI();
ImageDownloader imageDownloader = new ImageDownloader(imageView, progressBar/*,imageDownloader*/);
progressBar.setVisibility(View.VISIBLE);
imageDownloader.execute(urls.get(i));
imageDownloader = null;
i++;
}
}
}